Files
2025-09-08 09:52:22 +08:00

104 lines
2.5 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
namespace Lesson10_封装_运算符重载联系
{
#region 知识点一 基本概念
//概念
//让自定义类和结构体
//能够使用运算符
//使用关键字
//operator
//特点
//1.一定是一个公共的静态方法
//2.返回值写在operator前
//3.逻辑处理自定义
//作用
//让自定义类和结构体对象可以进行运算
//注意
//1.条件运算符需要承兑实现
//2.一个符号可以多个重载
//3.不能使用ref和out
#endregion
#region 知识点二 基本语法
//public static 返回值类型 operator 运算符(参数列表){}
#endregion
#region 知识点三 实例
class Point
{
public int x;
public int y;
public static Point operator +(Point p1,Point p2)
{
Point p = new Point();
p.x = p1.x + p2.x;
p.y = p1.y + p2.y;
return p;
}
public static Point operator +(Point p1, int value)
{
Point p = new Point();
p.x = p1.x + value;
p.y = p1.y + value;
return p;
}
public static Point operator +(int value, Point p1)
{
Point p = new Point();
p.x = p1.x + value;
p.y = p1.y + value;
return p;
}
}
#endregion
#region 知识点五 可重载和不可重载的运算符
#region 可重载
//注意运算所需的参数数量
//算术运算符
//- * / % ++ --都可以
//逻辑运算符
//!可以
//位运算符
//| & ^ ~ >> << 可以
//条件运算符
//>= <= == < >需要成对出现(写了>的就要写<的)
//一般返回值都是bool也可以是其他值
#endregion
#region 不可重载
//逻辑与&& 逻辑或||
//索引符[]
//强转运算符()
//特殊运算符
//点. 三目运算符 赋值号=
#endregion
#endregion
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
#region 知识点四 使用
Point p = new Point();
p.x = 1;
p.y = 1;
Console.WriteLine(p.x+" "+p.y);
Point p2 = new Point();
p2.x = 2;
p2.y = 2;
Console.WriteLine(p2.x + " " + p2.y);
Point p3 = p + p2;
Console.WriteLine(p3.x + " " + p3.y);
Point p4 = p3 + 2;
Point p5 = 3 + p4;
#endregion
}
}
}