C ++ Operators and Arguments

Say I have a Point class:

class Point {
    int x, y;
public:
    Point& operator+=(const Point &p) { x=p.x; y=p.y; return *this; }
};

Why can't I call it the following:

Point p1;
p1 += Point(10,10);

And is there a way to do this while still having the link as an argument?

+3
source share
3 answers

Here is the code you need:

class Point {
    int x,y;
public:
    Point(int x=0,int y=0) : x(x), y(y) {}
    Point& operator+=(const Point&p) {x+=p.x;y+=p.y;return *this;}
};

As Conrad noted, you need a constructor. You also need to explicitly complete the additions to your operator overload.

+8
source

Why can't I call it the following:

Because you forgot to declare the appropriate constructor. Other than that, this call looks fine.

(In addition, the code inside yours is operator +=incorrect: it overwrites the values ​​instead of doing the additions).

+11
source

. , ints:

class Point {
public:
  Point() : x( 0 ), y( 0 ) { }
  Point( int _x, int _y ) : x( _x ), y( _y ) { }
// rest of the code
};

Note: if you declare a constructor that accepts some arguments, then to create an instance, such as Point x;, you need to declare the default constructor yourself.

PS Just read Conrad's answer. Yes, you can use +=, not =for your members. :)

+4
source

Source: https://habr.com/ru/post/1711988/


All Articles