[英]overloading shift left and shift right operator (cin and cout)
我已经在这里上过Point课。 我写的时候一切都很好
cout << p1 << endl; //which p is a Point
但是当我有两个指向和写的对象时
cout << (p1 + p2) << endl; //or (p1 - p2) and etc...
我得到错误。 您可以在此处看到错误。 我不知道原因 请帮忙。
您的问题是您试图将右值传递到接受非常量左值引用的函数中。 这是无效的 。 要解决此问题,只需使用const引用的Point
参数:
ostream &operator<<(ostream &output, const Point &p);
错误应该来自输出运算符签名:而不是:
ostream &operator<<(ostream &output, Point &p){
output << '(' << p._x << ", " << p._y << ')';
return output;
}
你应该有:
ostream &operator<<(ostream &output, const Point &p) { // notice const here
output << '(' << p._x << ", " << p._y << ')';
return output;
}
这是因为(p1 + p2)
返回一个临时值,并且需要绑定到const引用。
这是更正的代码
您需要添加const
说明符,像这样
ostream &operator<<(ostream&, const Point&);
这是题外话,但您的输入将无法与输出一起使用,因为您读取了两个以空格分隔的双精度型,但将其括在括号和逗号中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.