1. What is Operator overload?
Definition:(Defined in Encyclopedia)It is to redefine the defined operators with certain functions to complete more detailed operations and other functions. Operator overloading can embody general abstract operators to facilitate external calls without having to know the specific internal operation process.
2. Why is Operator overloading required?
In C #, the built-in data types include: int, double, and so on. You can directly add or subtract values. For example: int I, j = 1; int sum = I + J; you can directly obtain the desired sum.
If you want to compare a class (structure) for object comparison and addition, subtraction, and other operations, how can this be achieved? For example, how does one add a + B to an object named test with objects A and B?
3. Operator Overloading
Formula:Public static "return type" operator "operator symbol "{............}
Eg: public static test operator + (test LHS, test RHs) {return new test (LHS. Value + RHS. value );}
4. Case studies
Struct Test { Private Int Value; Public Int Value { Get { Return Value ;}} Public Test ( Int Ivalue ){ This . Value = Ivalue ;} // C # Operator Overloading // 1. Declare a binary operator and add two tests together. Public Static TestOperator + (Test LHS, test RHs ){ Return New Test (LHS. Value + RHS. Value );} // 2. Declare a binary operator and add Test and INT together. Public Static Test Operator + (Test LHS, Int RHS ){ Return LHS +New Test (RHs );} // 3. Declare a binary operator and add int and test together. Public Static Test Operator + ( Int LHS, test RHs ){ Return New Test (LHS) + RHS ;} // 4. Declare a unary operator, Public Static Test Operator ++ (Test h) {H. Value ++ ; Return H ;}}
Define a structure, which is of course the same as a class.
Result:
Operation-related operations can only be performed if defined, for example, above 3:Add int and test together. Only int + test objects can be added. If 2.3 + test objects are added, an error is returned.
5. Note
C # has six comparison operators, which are divided into three pairs:
● = And! =
●> And <
●>=And <=
C # The comparison operator must be reloaded in pairs. If = is reloaded, it must also be reloaded! =. Otherwise, a compilation error occurs.
6. Operators that can be overloaded (derived from C # advanced programming)
...... Learn New, take notes ......