我在为 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 '<<' : no operator found which takes a right-hand operand of type 'const T' (or there is no acceptable conversion)
最佳答案
你的 operator<<()
不适用于 const
对象,因为您已将其声明为
friend ostream& operator<<(ostream& os,T& t)
您需要告诉编译器您希望能够将它与const
一起使用对象:
friend ostream& operator<<(ostream& os, const T& t)
关于c++ - 将 operator<< 与 const 对象一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15367257/