C#之运算符重载学习案例

来源:互联网 发布:lomo拍立得知乎 编辑:程序博客网 时间:2024/06/06 18:44
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Override_test{    public class ComplexClass    {        public class complex        {            private float real;            private float img;            public complex(float p, float q)     //构造函数            {                real = p;                img = q;            }            public complex()     //构造函数            {                real = 0;                img = 0;            }            public void Print()            {                Console.WriteLine("{0}+{1}i", real, img);            }            public static complex operator +(complex Lhs, complex rhs)            {                complex sum = new complex();                sum.real = Lhs.real + rhs.real;                sum.img = Lhs.img + rhs.img;                return sum;            }            public static complex operator -(complex Lhs, complex rhs)            {                complex result = new complex();                result.real = Lhs.real - rhs.real;                result.img = Lhs.img - rhs.img;                return result;            }        }        static void Main()        {            complex A = new complex(10.5f, 12.5f);            complex B = new complex(8.0f, 4.5f);            complex C;            Console.Write("Complex Number A:");            A.Print();            Console.Write("Complex Number B:");            B.Print();            C = A + B;            Console.Write("\nA+B=");            C.Print();            C = A - B;            Console.Write("A-B=");            C.Print();        }    } }

0 0