繁体   English   中英

<< C ++中的运算符重载错误

[英]<< Operator overloading error in C++

我是C ++初学者,试图从在线视频中学习。 在操作员重载讲座中的示例时,会出现以下代码并给出错误

 error: no match for 'operator<<' in 'std::cout << operator+(((point&)(& p1)), ((point&)(& p2)))'compilation terminated due to -Wfatal-errors.

在标有评论的行上。 有人可以告诉代码中有什么问题吗? 我正在尝试教授在讲座中解释但无法编译的内容。

===============

#include <iostream>
using namespace std;


class point{
public:
    double x,y;
};

point operator+ (point& p1, point& p2)
{
    point sum = {p1.x + p2.x, p1.y + p2.y};
    return sum;
}

ostream& operator<< (ostream& out, point& p)
{
    out << "("<<p.x<<","<<p.y<<")";
    return out;
}


int main(int argc, const char * argv[])
{
    point p1 = {2,3};
    point p2 = {2,3};
    point p3;
    cout << p1 << p2;

    cout << p1+p2; // gives a compliation error
    return 0;
}

这只是const正确性的一个问题。 你的operator +返回一个临时的,所以在调用operator<<时你不能绑定非const引用。 签名:

ostream& operator<< (ostream& out, const point& p)

虽然您不需要这样做来修复此编译错误,但除非您修复operator+类似,否则您将无法添加const点:

point operator+(const point& p1, const point& p2)

将参数类型从point&更改为const point& for operator+operator<< 非const引用不能绑定到临时(由operator+返回),这会导致编译错误。

原因是第二个参数应该是const引用。 (你不希望它被修改,对吗?)所以,它就像,

std::ostream& operator<< (std::ostream &out, const Point &p)
{
    out << "(" << p.x << ", " << p.y << ")";

    return out;
}

暂无
暂无

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

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