C # allows user-defined types to overload operators by defining static member functions using the operator keyword
Let's look at an example:
Public classcomplexnumber{Private intReal; Private intimaginary; //Constructors PublicComplexNumber (intRinti) {real=R; Imaginary=i; } //overloads the ToString method, which is used to display ComplexNumber Public Override stringToString () {if(Imaginary >=0) return(System.String.Format ("{0}+{1}i", real, imaginary)); Else return(System.String.Format ("{0}-{1}i", real, imaginary)); }}
We need +,-to add or subtract two imaginary numbers, using the following method overload +,-operator
//Overloaded + operators Public StaticComplexNumberoperator+(ComplexNumber lhs,complexnumber rhs) {return NewComplexNumber (Lhs.real+rhs.real,lhs.imaginary+rhs.imaginary);}//Overloaded-Operator Public StaticComplexNumberoperator-(ComplexNumber lhs,complexnumber rhs) {return NewComplexNumber (Lhs.real-rhs.real,lhs.imaginary-rhs.imaginary);}
Operator overloading is declared in the same way as methods, but the operator keyword tells the compiler that it is actually an operator overload.
In this example
public static ComplexNumber operator+(ComplexNumber lhs,complexnumber RHS)
The overloaded operator "+" that represents the global static return value is the ComplexNumber type, the input parameter is a two-complexnumber variable, the return value is still complexnumber,
The action returned is to call the constructor in the ComplexNumber class and the ToString method.
public static implicit operator ComplexNumber (double D)
Where implicit represents the stealth type conversion, and D is converted from double to complexnumber type.
Public double D (get;set;)
is a forced type conversion form, meaning to cast to double type
C # Syntax Basics (ii)--operator overloading