重载左移和右移运算符(cin和cout)
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...
我有错误。你可以在这里看到错误。我不知道原因。请帮忙。
您的问题是试图将右值传递给接受非常量左值引用的函数。这是无效的。要解决此问题,只需使用常量引用的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
说明符,如以下
ostream &operator<<(ostream&, const Point&);
这是离题的,但您的输入不适用于输出,因为您读取了两个用空格分隔的双精度,但输出的是括号和逗号。
相关文章:
- 为什么 printf 在 C++ 中的执行速度比 cout 快?另外scanf比cin慢,为什么?
- 使用 CIN COUT 显示垃圾值的文件对象?
- 当我们声明 cin 为 int 并从 cin 中获取输入并在 cout 中打印 cin 时会发生什么?
- 为什么我的 cout 一次执行,尽管 cin 应该在两者之间读取?
- 两个 cin / cout 语句合并为一个
- 防止 cin、cout、cerr 被实例化
- 无法让我了解 cin.get 和 cout 在这里的工作方式
- 使用 std::endl 与 "n" 当 cin 和 cout 被解绑时
- CIN 和 COUT 如何在以下程序中工作
- 使用自定义宏来简化 cin 和 cout 语句等内容被认为是更好还是更差
- 简单的cin cout代码由"build and run"运行,但从bin/debug/x开始工作.exe
- 通过 cin/cout 的协议单元测试 - 如何阻止流以等待内容?
- 为什么 CIN / COUT 比 scanf/printf 慢
- 从printf-scanf转换为cin-cout时出现问题
- cin/cout 使用什么技术/模式允许例如 cout << x << y
- 为什么我不能将 cin/cout 放在一个函数中并从 main() 调用该函数
- 交替使用cin/cout很慢
- 关于 cin/cout 过载的简单问题 4.
- cin / cout being skipped
- c++, cin, cout, threads和sync_with_stdio的输出损坏