【问题标题】:Using operator<< with const object将 operator<< 与 const 对象一起使用
【发布时间】:2013-03-12 16:50:13
【问题描述】:
我在为 const 对象重载运算符
#include <iostream>
using namespace std;
class T
{
friend ostream& operator<<(ostream& os,T& t)
{
os << "Val : " << t.value << endl;
return os;
}
private:
int value;
public:
T(int v) { value=v; }
int getValue() const { return value; }
};
int main()
{
const T t(2);
cout << t;
return 0;
}
编译器消息:
error C2679: binary '
【问题讨论】:
标签:
c++
operator-overloading
【解决方案1】:
您的 operator<<() 不适用于 const 对象,因为您已将其声明为
friend ostream& operator<<(ostream& os,T& t)
您需要告诉编译器您希望能够将其与const 对象一起使用:
friend ostream& operator<<(ostream& os, const T& t)
【解决方案2】:
您的operator<< 通常应通过const 引用来获取其参数:
friend ostream& operator<<(ostream& os, const T& t)
非const 引用不能绑定到const 对象。这是有道理的,否则您可以通过引用修改const 对象。
【解决方案3】:
只需添加一个 const 就可以了:
friend ostream& operator<<(ostream& os,const T& t)
【解决方案4】:
将T& 设为const 引用:
friend ostream& operator<<(ostream& os,T& t)
这样就变成了:
friend ostream& operator<<(ostream& os,const T& t)
或者,去掉&:
friend ostream& operator<<(ostream& os,T t)
两者都会在您的代码中给出以下结果:
Val : 2
在控制台中。