简体   繁体   English

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

[英]overloading shift left and shift right operator (cin and cout)

I've already made a Point class here . 我已经在这里上过Point课。 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: 要解决此问题,只需使用const引用的Point参数:

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. 这是因为(p1 + p2)返回一个临时值,并且需要绑定到const引用。

Here is corrected code 是更正的代码

You need to add const specifier, like this 您需要添加const说明符,像这样

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. 这是题外话,但您的输入将无法与输出一起使用,因为您读取了两个以空格分隔的双精度型,但将其括在括号和逗号中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM