130
Binary Operator Overloading
What operator overloading does is simplify
this syntax and thereby
provide a more intuitive interface for the class. To convert the Add method
to an overload method for the addition sign,
replace the name of the
method with the operator keyword followed by the operator that is to be
overloaded. The whitespace between the keyword and the operator can
optionally be left out. Note that for an operator
overloading method to
work, it must be defined as both public and static.
class MyNum
{
public int val;
public MyNum(int i) { val = i; }
public static MyNum operator +(MyNum a, MyNum b) {
return new MyNum(a.val + b.val);
}
}
Since the class now overloads the addition sign, this operator can be
used to perform the desired calculation.
MyNum a = new MyNum(10), b = new MyNum(5);
MyNum c = a + b;
Unary Operator Overloading
Addition is a binary
operator, because it takes two operands. To overload a
unary operator, such as increment (++), a single method parameter is
used instead.
Chapter 22 OperatOr OverlOading
131
public static MyNum operator ++(MyNum a)
{
return new MyNum(a.val + 1);
}
Note that this will overload both the postfix
and prefix versions of the
increment operator.
MyNum a = new MyNum(10);
a++;
++a;
Do'stlaringiz bilan baham: