我在重载运算符时遇到了问题<<对于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;
}
编译器消息:
错误C2679:二进制'&lt;&lt;' :找不到哪个操作员需要右手 'const T'类型的操作数(或没有可接受的转换)
答案 0 :(得分:2)
您的operator<<()
无法使用const
对象,因为您已将其声明为
friend ostream& operator<<(ostream& os,T& t)
您需要告诉编译器您希望能够将它与const
个对象一起使用:
friend ostream& operator<<(ostream& os, const T& t)
答案 1 :(得分:1)
您的operator<<
通常应该通过const
参考:
friend ostream& operator<<(ostream& os, const T& t)
非const
引用无法绑定到const
对象。这是有道理的,否则您将能够通过引用修改const
对象。
答案 2 :(得分:0)
在行中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
在控制台中。
答案 3 :(得分:0)
只需添加一个const就可以了:
friend ostream& operator<<(ostream& os,const T& t)