目录
1.基本概念
让自定义类和结构体能够使用运算符。
关键字:operator.
特点:一定是一个公共的静态方法,返回值写在operator的前面,逻辑处理自定义。
作用:让自定义类和结构体对象可以进行运算。
注意:条件运算符需要成队实现,一个符号可以多个重载,不能使用ref和out.
2.基本语法
public static 返回类型 operator 运算符(参数列表)
3.实例
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;
}
4.使用
Point p=new Point();
p.x=1;
p.y=1;
Point p2=new Point();
p2.x=2;
p2.y=2;
Point p3=p+p2;
Point p4=p3+2;
可以重载。加法参数最多写两个。
5.可重载与不可重载运算符。
①算数运算符都可以重载
注意符号是一个参数还是两个参数。
public static Point operator-(Point p1,Point p2)
{
return null;
}
public static Point operator(Point p1,Point p2)
{
return null;
}
public static Point operator/(Point p1,Point p2)
{
return null;
}
public static Point operator%(Point p1,Point p2)
{
return null;
}
public static Point operator++(Point p1)
{
return null;
}
public static Point operator--(Point p1)
{
return null;
}
②逻辑运算符
注意:符号需要两个参数还是一个参数,逻辑或和逻辑与是没有运算符重载的。
public static bool operator||(Point p1)
{
return false;
}
③位运算符
注意:符号需要一个还是两个参数。
public static Point operator|(Point p1,Point p2)
{
return null;
}
public static Point operator&(Point p1,Point p2)
{
return null;
}
public static Point operator^(Point p1,Point p2)
{
return null;
}
public static Point operator~(Point p1)
{
return null;
}
public static Point operator>>(Point p1,int num)
{
return null;
}
④条件运算符
条件运算符必须成对出现。
返回值一般是bool类型,也可以是其他的,相关符号必须配对实现。
public static bool operator>(Point p1,Point p2)
{
return false;
}
public static bool operator<(Point p1,Point p2)
{
return false;
}
public static bool operator>=(Point p1,Point p2)
{
return false;
}
public static bool operator<=(Point p1,Point p2)
{
return false;
}
public static bool operator==(Point p1,Point p2)
{
return false;
}
public static bool operator!=(Point p1,Point p2)
{
return false;
}
⑤不可以重载的运算符
逻辑与(&&),逻辑或(| |)
索引符[ ]
强转运算符()
特殊运算符
点(.) 三目运算符?: 赋值符号=