1

I've already made a Point class here. Everything works fine when I write

cout << p1 << endl; //which p is a Point

but when I have two objects of Point and write

cout << (p1 + p2) << endl; //or (p1 - p2) and etc...

i get errors. You can see the errors here. I don't know the reason. please help.

Roozbeh
  • 77
  • 6
  • Please add whether `p1+p2` isoltatedly works. If it doesn't, then re-write your question to contain the minimum code necessary to produce the error. Also, you forgot to add the error. Add it directly to your question, it's most likely crucial to the answer. – Marcus Müller Feb 19 '15 at 14:04
  • 1
    I'm afraid we can't see the errors here. Please add them (in text), **after** searching for the error. This question may very well be a duplicate. – MSalters Feb 19 '15 at 14:04

3 Answers3

5

Your issue is that you are attempting to pass an rvalue into a function which accepts a non-const lvalue reference. This is invalid. To fix the issue, just take the Point argument by const reference:

ostream &operator<<(ostream &output, const Point &p);
Community
  • 1
  • 1
TartanLlama
  • 63,752
  • 13
  • 157
  • 193
3

The error should come from the output operator signature: instead of having:

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

you should have:

ostream &operator<<(ostream &output, const Point &p) { // notice const here
    output << '(' << p._x << ", " << p._y << ')';
    return output;
}

This is because (p1 + p2) returns a temporary and that needs to bind to a const reference.

utnapistim
  • 26,809
  • 3
  • 46
  • 82
0

Here is corrected code

You need to add const specifier, like this

ostream &operator<<(ostream&, const Point&);

It's offtopic, but your input is would not work with output, since you read two doubles separated by space, but output it parentheses and comma.

Nikolay K
  • 3,770
  • 3
  • 25
  • 37