// Point p3 = Point.operator+ (p1, p2)
Point p3 = p1 + p2;
Likewise, p1 – p2 maps to the following:
// Point p4 = Point.operator- (p1, p2)
Point p4 = p1 - p2;
With this update, our program now compiles, and we find we are able to add and subtract
Point objects (see Figure 12-2).
Figure 12-2.
Redefining + and - for the Point type
Strictly speaking, when you are overloading a binary operator, you are not required to pass in
two parameters of the same type. If it makes sense to do so, one of the arguments can differ. For
example, here is an overloaded operator +, which allows the caller to obtain a new Point that is
based on a numerical adjustment:
public struct Point
{
...
public static Point operator +(Point p1, int change)
{
return new Point(p1.x + change, p1.y + change);
}
public static Point operator +(int change, Point p1)
{
return new Point(p1.x + change, p1.y + change);
}
}
We would now be able to use these new versions of operator + as follows:
Do'stlaringiz bilan baham: |