运算符重载

 

 

    class Program
    {
        static void Main(string[] args)
        {
            Complex c1 = new Complex(1, 2);
            Complex c2 = new Complex(3, 4);
            Complex c3 = c1 + c2;
            Console.WriteLine(c3);//4 + 6
            Console.ReadKey();
        }

    class Complex
    {
        public int x;
        public int y;

        public Complex(int x, int y)
        {
            this.x = x;
            this.y = y;
        }


        //必须是 static 方法
        public static Complex operator +(Complex c1, Complex c2)
        {
            return new Complex(c1.x + c2.x, c1.y + c2.y);
        }

        public override string ToString()
        {
            return $"{this.x} + {this.y}";
        }
    }

 

posted @ 2018-03-12 16:42  热敷哥  阅读(136)  评论(0编辑  收藏  举报