Suppose I define this structure:
struct Point {
double x, y;
};
How can I overload the + operator so that, declared,
Point a, b, c;
double k;
the expression
c = a + b;
yields
c.x = a.x + b.x;
c.y = a.y + b.y;
and the expression
c = a + k;
yields
c.x = a.x + k;
c.y = a.y + k; // ?
Will the commutative property hold for the latter case? That is, do c = a + k; and c = k + a; have to be dealt with separately?
Just do it:
With regards to your last question, the compiler makes no
assumptions concerning what your operator does. (Remember, the
+operator onstd::stringis not commutative.) So youhave to provide both overloads.
Alternatively, you can provide an implicit conversion of
doubletoPoint(by having a converting constructor inPoint). In that case, the first overload above will handleall three cases.