18

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?

wjmolina
  • 2,625
  • 2
  • 26
  • 35

4 Answers4

24

Just do it:

Point operator+( Point const& lhs, Point const& rhs );
Point operator+( Point const& lhs, double rhs );
Point operator+( double lhs, Point const& rhs );

With regards to your last question, the compiler makes no assumptions concerning what your operator does. (Remember, the + operator on std::string is not commutative.) So you have to provide both overloads.

Alternatively, you can provide an implicit conversion of double to Point (by having a converting constructor in Point). In that case, the first overload above will handle all three cases.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
  • Why do we have to declare the Point arguments as constants? – wjmolina Nov 21 '12 at 20:57
  • 2
    @JosuéMolina So that you can pass temporaries to them; you can't initialize a non-const reference with a temporary. Given the simplicity of `Point`, there's no problem in passing them directly by value, rather than by reference (in which case, whether they are `const` or not is irrelevant). But the ubiquitous convention is to pass class types by reference to const, and when conventions are truly ubiquitous, and don't cause other problems, it's probably best to abide by them, if only so that people don't wonder why you did it differently. – James Kanze Nov 22 '12 at 08:26
  • @JamesKanze wouldnt the const make it immutable? – Savannah Madison Jun 02 '21 at 13:36
11

Here is how I would do it.

struct Point {
   double x, y;
   struct Point& operator+=(const Point& rhs) { x += rhs.x; y += rhs.y; return *this; }
   struct Point& operator+=(const double& k) { x += k; y += k; return *this; }
};

Point operator+(Point lhs, const Point& rhs) { return lhs += rhs; }
Point operator+(Point lhs, const double k) { return lhs += k; }
Point operator+(const double k, Point rhs) { return rhs += k; }
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
6

In C++ there's only one difference between a struct and a class: in a struct the default visibility is public while in a class it is private.

Other than that you can do anything you would do in a class in a struct and it will look exactly the same.

Write operator overloading in a struct as you would in a class.

selalerer
  • 3,766
  • 2
  • 23
  • 33
4

This will also work:

struct Point{
    double x,y;
    Point& operator+(const Point& rhs){ 
            x += rhs.x;
            y += rhs.y;
            return *this;
    }
}
shrokmel
  • 173
  • 2
  • 9