First, let's look at the basic syntax for operator overloading.
To overload operators, you can add operators to the class (they must be static ).
Let's first look at a simple class:
Public class addclass1
{
Public int val;
}
This is only a wrapper of the int value, but it can be used to describe the rule.
ForCodeCannot be compiled:
Addclass1 OP1 = new addclass1 ();
Op1.val = 5;
Addclass1 OP2 = new addclass1 ();
Op2.val = 5;
Addclass1 OP3 = OP1 + OP2;
The error is that the + operator cannot be applied to the addclass1 type operand, because we have not defined the operation to be executed.
Although the following code can be executed, we cannot get the expected results:
Addclass1 OP1 = new addclass1 ();
Op1.val = 5;
Addclass1 OP2 = new addclass1 ();
Op2.val = 5;
Bool OP3 = OP1 = OP2;
This only uses the binary operator = to determine whether OP1 and OP2 are referenced by an object, rather than verifying that their values are equal. In this Code, OP3 is false even if op1.val and op2.val are equal. Because they reference not the same object.
We use the following method to overload the + operator.
Public class addclass1
{
Public int val;
Public static addclass1 operator + (addclass1 OP1, addclass1 OP2)
{
Addclass1 returnval = new addclass1 ();
Returnval. Val = op1.val + op2.val;
Return returnval;
}
}
The reload of all binary operators is basically similar to this. The unary operator looks similar, but there is only one parameter.
Public static addclass1 operator-(addclass1 OP1)
{
Addclass1 returnval = new addclass1 ();
Returnval. Val =-op1.val;
Return returnval;
}
Next we will look at an example of object operations of different classes.
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 class addclass3
{
Public int val;
}
For this type of definition, the following code can also be executed:
Addclass1 OP1 = new addclass1 ();
Op1.val = 5;
Addclass2 OP2 = new addclass2 ();
Op2.val = 5;
Addclass3 OP3 = OP1 + OP2;
This is because the addition operator defined in addclass1 is only suitable for adding addclass1 and addclass2 and then assigning them to addclass3. In addition, the order must be before the addclass1 object and the addclass2 object after this addition. to reverse the order, unless we reload an operator in the reversed order, this is not supported.Algorithm.
The following operators can be reloaded:
Unary operator: + ,-,!, ~, ++, --, True, false
Binary operators: +,-, *,/, %, &, |, ^, <,>
Comparison OPERATOR: = ,! =, <,>, <=,> =
If you want to reload =, you must also reload it! =