重载左移和右移运算符(cin和cout)

overloading shift left and shift right operator (cin and cout)

本文关键字:cin cout 运算符 左移 右移 重载      更新时间:2023-10-16

我已经在这里创建了一个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&);

这是离题的,但您的输入不适用于输出,因为您读取了两个用空格分隔的双精度,但输出的是括号和逗号。