C # allows you to overload operators for your own classes. In this way, user-defined data types can be used as natural and reasonable as basic data types. For example, you can create a new data type named complexnumber to represent a complex number, and provide a method to perform mathematical operations on such numbers using standard Arithmetic Operators, for example, use the + operator to add two complex numbers.
To overload an operator, you can compile a function and add the symbol of the operator to be reloaded after its naming operator. For example, you can use the following methods to overload the + operator:
Public static complexnumber operator + (complexnumber A, complexnumber B)
All operators are reloaded as static methods of classes. In addition, you must also note that when you reload the equal operator (=), you must also load the unequal operator (! = ). The <and> and <= and> = operators must also be reloaded in pairs.
The following is a complete list of operators that can be reloaded:
- Unary operators: +,-, and ,-,! ,~ , ++, --, True, false
- Binary operators: +,-, *,/, %, &, |, ^, <, >>, = ,! =,>, <, >=, <=
The followingCodeIn the example, create a complexnumber class for the overload + and-operators:
Code
Public Class Complexnumber
{
Private Int Real;
Private Int Imaginary;
Public Complexnumber (): This ( 0 , 0 ) // Constructor
{
}
Public Complexnumber ( Int R, Int I) // Constructor
{
Real = R;
Imaginary = I;
}
// Override tostring () to display a complex number in the traditional format:
Public Override String Tostring ()
{
Return (System. String. Format ( " {0} + {1} I " , Real, imaginary ));
}
// Overloading '+ 'operator:
Public Static Complexnumber Operator + (Complexnumber A, complexnumber B)
{
Return New Complexnumber (A. Real + B. Real, A. Imaginary + B. Imaginary );
}
// Overloading '-'operator:
Public Static Complexnumber Operator - (Complexnumber A, complexnumber B)
{
Return New Complexnumber (A. Real - B. Real, A. Imaginary - B. Imaginary );
}
}
With this class, you can use the following code to create and operate two complex numbers:
Code
Class Testcomplexnumber
{
Static Void Main ()
{
Complexnumber = New Complexnumber ( 10 , 12 );
Complexnumber B = New Complexnumber ( 8 , 9 );
System. Console. writeline ( " Complex Number A = {0} " , A. tostring ());
System. Console. writeline ( " Complex Number B = {0} " , B. tostring ());
Complexnumber sum = A + B;
System. Console. writeline ( " Complex Number sum = {0} " , Sum. tostring ());
Complexnumber difference = A - B;
System. Console. writeline ( " Complex Number Difference = {0} " , Difference. tostring ());
}
}
For exampleProgramAs shown in, you can now use the addition and subtraction operators for objects of the complexnumber class in a very intuitive way. The result is as follows:
Complex Number A = 10 + 12i
Complex Number B = 8 + 9i
Complex Number sum = 18 + 21i
Complex Number Difference = 2 + 3I