The operator keyword is used to overload built-in operators using the following methods:
Public classoperatorcontroller:controller{// //GET:/operator/ Public intnum, den; PublicOperatorcontroller (intNumintden) { This. num =num; This. den =den; } //overload operator + Public StaticOperatorcontrolleroperator+(Operatorcontroller A, Operatorcontroller b) {return NewOperatorcontroller (A.num * b.den + b.num *A.den, A.den*B.den); } //overload operator * Public StaticOperatorcontrolleroperator*(Operatorcontroller A, Operatorcontroller b) {return NewOperatorcontroller (A.num * b.num, A.den *B.den); }}
The Operatorcontroller class above provides an overloaded method for constructors and "+", "*".
Here is a set of execution codes:
var New Operatorcontroller (12); var New Operatorcontroller (37); var New Operatorcontroller (23); var d = a + b; var e = A * b + C;
For the sake of understanding, I will execute the variable one by one output in the process:
A
Response.Write ("A:""--""<br/> ");
Output:a:1--2
B
Response.Write ("B:""--""< br/>");
Output: b:3--7
C
Response.Write ("C:""--""<br/> ");
Output: b:2--3
D
Response.Write ("D:""--""<br />");
Output: d:13--14
E
Response.Write ("e:""--""<br/> ");
Output: e:37--42
Next, focus on how the overloaded "+" is implemented:
Take var d = a + B; For example, break down the execution process,
Step1. Perform a "+" overloaded method
Public Static operator +(Operatorcontroller A, Operatorcontroller b) { returnnew Operatorcontroller (A.num * b.den + b.num ** b.den);}
When A and B are "+" operations, A and B are passed as parameters to this overloaded method (the overloaded operator only supports two parameters ), the operation can be transformed into
Public Static operator +(Operatorcontroller A, Operatorcontroller b) { returnnew Operatorcontroller (+);}
Step2. Execute constructor
Public Operatorcontroller (intint den) {This . num = num; this. den = den;}
So Execute Response.Write ("D:" + D.num + "--" + D.den + "<br/>"), Output d:13--14
Operator overload keyword operator