2014-02-06 44 views
1

我是一名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; 
} 
+0

谢谢大家。这工作。 – kaushal

回答

3

这只是const正确性的一个问题。您的话务员+会返回一个临时号码,因此在拨打operator<<时,您不能绑定非const号码的参考号码。请签名:

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

虽然你不需要做来解决这个编译错误,您将无法添加const点,除非你解决operator+类似:

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

“您的运营商+返回一个临时的,所以当您呼叫运营商<<” - 这是不明显的,你不能绑定非const引用。它在C++标准的某个地方吗? –

+0

谢谢Tony的详细解释。 – kaushal

+0

@SergiiKhaperskov:它包含在8.5.3/5中,参见“否则,引用应该是对非易失性常量类型的左值引用(即cv1应该是const),或者引用应该是右值引用。和示例“double&rd2 = 2.0; //错误:不是左值,参考不是​​const”。 –

0

变化从point&const point&参数类型为operator+operator<<。非const引用不能绑定到临时(由operator+返回)并且导致编译错误。

+0

感谢您的解释。你先回答! :) – kaushal

0

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

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

    return out; 
}