学习C#运算符重载

C#运算符重载

 


//运算符重载使自定义类型和结构体对象可以与其他类型进行运算

运算符重载的实现

实例:

class Point
{
public Point(int x,int y)
{
this.x = x;
this.y = y;
}
public 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;
}
}

class Program
{
static void Main(string[] args)
{
Point p1 = new Point(1, 1);
Point p2 = new Point(2, 2);
Point p3 = p2 + p1;
Point p4 = p2 + 3;
Console.WriteLine("{0}\n{1}",p3.x,p3.y);
Console.WriteLine("{0}\n{1}", p4.x, p4.y);
}
}

可重载和不可重载运算符

下表描述了C#中运算符重载的能力

+, -, !, ~, ++, --这些一元运算符只有一个操作数,且可以被重载。
+, -, *, /, % 这些二元运算符带有两个操作数,且可以被重载。
==, !=, <, >, <=, >= 这些比较运算符可以被重载。
&&, || 这些条件逻辑运算符不能被直接重载。
+=, -=, *=, /=, %= 这些赋值运算符不能被重载。
=, ., ?:, ->, new, is, sizeof, typeof 这些运算符不能被重载。

 

posted on 2020-05-16 16:29  无畏勇者城之内  阅读(167)  评论(0编辑  收藏  举报