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.
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);
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.