示例#1
0
        public static void SimpleOperatorOverload()
        {
            OperatorClass op1 = new OperatorClass(1);
            OperatorClass op2 = new OperatorClass(1);

            // 调用重载的操作符
            OperatorClass op3 = op1 + 1;
            OperatorClass op4 = 1 + op1;
            OperatorClass op5 = op1 + op2;

            Console.WriteLine("op1 " + op1.ToString());
            Console.WriteLine("op2 " + op2.ToString());
            Console.WriteLine("op3 " + op3.ToString());
            Console.WriteLine("op4 " + op4.ToString());
            Console.WriteLine("op5 " + op5.ToString());

            // operator+=自动调用operator+的重载
            op4 += 3;
            op5 += op4;
            Console.WriteLine("op4 " + op4.ToString());
            Console.WriteLine("op5 " + op5.ToString());

            // 调用重载的operator==和operator!=
            bool b1 = op4 == op5;
            bool b2 = op4 != op5;
            bool b3 = op1 == op2;

            Console.WriteLine("{0} {1} {2}", b1, b2, b3);
        }
示例#2
0
        public static OperatorClass operator +(OperatorClass lhs, int rhs)
        {
            OperatorClass oc = new OperatorClass(lhs);

            oc.value += rhs;
            return(oc);
        }
示例#3
0
        public static OperatorClass operator +(int lhs, OperatorClass rhs)
        {
            OperatorClass oc = new OperatorClass(rhs);

            oc.value += lhs;
            return(oc);
        }
示例#4
0
 // 拷贝构造
 public OperatorClass(OperatorClass rhs)
 {
     this.value = rhs.value;
 }
示例#5
0
        public static void SimpleOperatorOverload()
        {
            OperatorClass op1 = new OperatorClass(1);
            OperatorClass op2 = new OperatorClass(1);

            // 调用重载的操作符
            OperatorClass op3 = op1 + 1;
            OperatorClass op4 = 1 + op1;
            OperatorClass op5 = op1 + op2;

            Console.WriteLine("op1 " + op1.ToString());
            Console.WriteLine("op2 " + op2.ToString());
            Console.WriteLine("op3 " + op3.ToString());
            Console.WriteLine("op4 " + op4.ToString());
            Console.WriteLine("op5 " + op5.ToString());

            // operator+=自动调用operator+的重载
            op4 += 3;
            op5 += op4;
            Console.WriteLine("op4 " + op4.ToString());
            Console.WriteLine("op5 " + op5.ToString());

            // 调用重载的operator==和operator!=
            bool b1 = op4 == op5;
            bool b2 = op4 != op5;
            bool b3 = op1 == op2;
            Console.WriteLine("{0} {1} {2}", b1, b2, b3);
        }
示例#6
0
 public static OperatorClass operator +(int lhs, OperatorClass rhs)
 {
     OperatorClass oc = new OperatorClass(rhs);
     oc.value += lhs;
     return oc;
 }
示例#7
0
 public static OperatorClass operator +(OperatorClass lhs, int rhs)
 {
     OperatorClass oc = new OperatorClass(lhs);
     oc.value += rhs;
     return oc;
 }
示例#8
0
 // 拷贝构造
 public OperatorClass(OperatorClass rhs)
 {
     this.value = rhs.value;
 }