0

I create the class 'Point', overload the operator '+' between 2 Point object and the operator '<<' to show the Point object. I can't compile and run the code. The error is that there is no operator "<<" matched. This is occured to "cout << "p3: " << (p1+p2) << endl;"

 class Point {
    public:
        Point(int x=0, int y=0) : _x(x), _y(y) {};
        Point operator +(Point &p);
        int getX() {
            return _x;
        }
        int getY() {
            return _y;
        }
        friend ostream& operator <<(ostream& out, Point &p);
    private:
        int _x, _y;
    };

    Point Point::operator +(Point &p) {
        Point np(this->_x+p.getX(), this->_y+p.getY());
        return np;
    }

    ostream& operator <<(ostream &out, Point &p) {
        out << '(' << p._x << ',' << p._y << ')';
        return out;
    }

    int main() {
        Point p1(1, 2);
        Point p2;
        cout << "p1: " << p1 << endl;
        cout << "p2: " << p2 << endl;
        cout << "p3: " << (p1+p2) << endl;
        system("pause");
        return 0;
    }
dongdong
  • 1
  • 1

3 Answers3

2

The expression

(p1+p2)

is an rvalue. The function

ostream& operator <<(ostream &out, Point &p)

expects a reference to Point. You can't pass an rvalue to this function. Change it to

ostream& operator <<(ostream &out, const Point &p)

in the declaration and the definition.

Thomas Sablik
  • 16,127
  • 7
  • 34
  • 62
2

C++ only allows a temporary to be passed to a const reference. See this: How come a non-const reference cannot bind to a temporary object?

Modify a temporary is meaningless. You need to define a const reference to promise you won't modify it and extend its lifetime.

Zhen Yang
  • 83
  • 9
1

When overloading operators, const correctness is not optional. The following prototypes are what you require...

        Point operator + (const Point &p) const;
        friend ostream& operator <<(ostream& out, const Point &p);
robthebloke
  • 9,331
  • 9
  • 12
  • Why do you think so? Is this a compiler extension? Do you have a reference for required constness in operator+?https://wandbox.org/permlink/72yCgKftGGHVEIsi – Thomas Sablik Oct 14 '19 at 05:19
  • Ok, so you recommend it for possible special cases in the future but in the current example in the question it's not required, is it? It would be even possible to change the arguments. Of course you can't pass rvalues in that case. – Thomas Sablik Oct 14 '19 at 05:33
  • `Point operator + (Point &p) { ++p._x; ++_x; return *this; }` is valid but not recommended. – Thomas Sablik Oct 14 '19 at 05:42