操作符重载

来源:互联网 发布:linux中ll命令 编辑:程序博客网 时间:2024/05/19 10:56

1.二元操作符重载,通常被要求配套重载。(如>和<要一起被重载)

2.C#提供operator关键字来允许自定义类型对内建操作符做出不同的反应,operator关键字只可与static关键字联合使用。

3.自定义类操作符重载示例:

public class Point
    {
        public int X { get; set; }
        public int Y { get; set; }
        public Point(int x, int y)
        {
            this.X = x;
            this.Y = y;
        }
        public static Point operator +(Point p1, Point p2)
        {
            return new Point(p1.X + p2.X, p1.Y + p2.Y);
        }

public static Point operator ++(Point p1)  //重载一元操作符
        {
            return new Point(p1.X + 1, p1.Y + 1);
        }

    }

4.如果一个类型重载了相关的二元操作符,这些简写的赋值操作符会自动具有新功能  (+=  、-=)。

0 0
原创粉丝点击