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); }
public static OperatorClass operator +(OperatorClass lhs, int rhs) { OperatorClass oc = new OperatorClass(lhs); oc.value += rhs; return(oc); }
public static OperatorClass operator +(int lhs, OperatorClass rhs) { OperatorClass oc = new OperatorClass(rhs); oc.value += lhs; return(oc); }
// 拷贝构造 public OperatorClass(OperatorClass rhs) { this.value = rhs.value; }
public static OperatorClass operator +(int lhs, OperatorClass rhs) { OperatorClass oc = new OperatorClass(rhs); oc.value += lhs; return oc; }
public static OperatorClass operator +(OperatorClass lhs, int rhs) { OperatorClass oc = new OperatorClass(lhs); oc.value += rhs; return oc; }