namespace chapter11{public class AddClass1 {public int val; public static ADDCLASS3 operator + (AddClass1 OP1, AddClass2 op2) { AddClass3 returnval = new AddClass3 (); Returnval.val = Op1.val + op2.val; return returnval; } } public class AddClass2 {public int val; public static ADDCLASS3 operator + (AddClass1 OP1, AddClass2 OP2)//Note Do not add the same operator to more than one class because it is not clear which operator to use //{ // ADDCLASS3 returnval = new AddClass3 (); returnval.val = Op1.val + op2.val; return returnval; } } public class ADDCLASS3 {public int val; } Class program { static void Main (string[] args) { AddClass1 OP1 = new AddClass1 (); Op1.val = 5; AddClass2 OP2 = new AddClass2 (); Op2.val = 5; ADDCLASS3 op3 = Op1 + Op2;}}}
operator overloading in mixed mode:namespacechapter11{ Public classAddClass1 { Public intVal; Public StaticAddClass3operator+(AddClass1 OP1, AddClass2 op2) {ADDCLASS3 returnval=NewADDCLASS3 (); Returnval.val= Op1.val +Op2.val; returnReturnVal; } } Public classAddClass2 { Public intVal; //Public static ADDCLASS3 operator + (AddClass1 OP1, AddClass2 op2)//be careful not to add the same operator to more than one class because it is not clear which operator to use// { //ADDCLASS3 returnval = new ADDCLASS3 (); //returnval.val = Op1.val + op2.val; //return returnval; //} } Public classADDCLASS3 { Public intVal; } classProgram {Static voidMain (string[] args) {AddClass1 OP1=NewAddClass1 (); Op1.val=5; AddClass2 OP2=NewAddClass2 (); Op2.val=5; ADDCLASS3 OP3= Op1 +OP2; } }}
View Code
When using a mixed type, the operands must be in the same order as the operator overloads, unless another overloaded operator and an inverted parameter are provided;
Overloaded operators: operator type members added to a class must be static.
Such as:
1 Public classAddClass12 {3 Public intVal; 4 Public StaticAddClass1operator+(AddClass1 OP1, AddClass1 op2)5 {6AddClass1 ReturnVal =NewAddClass1 ();7Returnval.val = Op1.val +Op2.val;8 returnReturnVal; 9 }Ten}
Operators that can be overloaded:
Unary operators: +,-,!, ~,++,--, true,false
Binary operators: +,-, *,%,&,/,|,^,<<,>>
Comparison operator: ==,!=,<,>,<=,>=
If the true and false operators are overloaded, you can use a class in a Boolean expression, for example (if (OP1) {}).
C # operator overloading