Use the operator keyword to overload the built-in operators, or provide user-defined conversions in the class or structure declaration.
In C #, operators are all static methods. The return value indicates the operation result, and its parameter is the operand. when we create an operator for a class, we call it "OverLoad", which is similar to the member method OverLoad. to overload the addition operator (+), write as follows:
Public static Fraction operator + (Fraction lhs, Fraction rhs );
It is my habit to name the parameters lhs and rhs. The parameter name lhs represents "lefthand side" (left-hand side). This reminds me that the first parameter represents the left side of the operation. similarly, rhs stands for "righthand side" (right hand side ).
The operator symbol overload Syntax of C # is to write the keyword operator after the operator to be reloaded. This keyword is a method modifier. Therefore, to reload the addition operator (+), it should be written as operator +.
C # You can implicitly convert int to long and explicitly convert long to int.int to long, because any int can adapt to the memory representation of long. the inverse operation, from long to int, must be explicit (use the forced conversion operator), because the conversion may cause information loss:
Int myInt = 5;
Long myLong;
MyLong = myInt; // implicit
MyInt = (int) myLong; // explicitly
The same function may be required for scores. For a given int, implicit conversion to scores is supported, because the integer is equal to the value divided by 1 (for example, 15 = 15/1 ).
For a given score, you can provide an explicit conversion to an integer, as long as the allowed value can be an integer. Therefore, 9/4 can be converted to an integer. 2.
Tip: the keyword implicit is used when the conversion is successful and the information will not be lost; otherwise, the explicit will be used.
Public static implicit operator Fraction (int theInt ){
Return new Fraction (theInt );
}
Public static explicit operator int (Fraction theFraction ){
Return theFraction. numerator/theFraction. denominator;
}
After the conversion operator symbol is equal to the operator (=) and not equal to the operator (! =). Remember, if one of them is implemented, the other must be implemented.
Public static bool operator = (Fraction lhs, Fraction rhs ){
Console. WriteLine ("In operator = ");
If (lhs. denominator = rhs. denominator & lhs. numerator = rhs. numerator)
Return true;
Return false;
}
Public static bool operator! = (Fraction lsh, Fraction rhs ){
Console. WriteLine ("In operator! = ");
Return! (Lhs = rhs );