c++ - 将 operator<< 与 const 对象一起使用

标签 c++ operator-overloading

我在为 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/

相关文章:

c++ - 链表运算符重载问题

c# - 在自定义 C# 类型中实现数学函数?

C++ operator+ 和 operator+= 重载

C++ - 包含 3 个元素的列表的类

c++ - 写入文件的最后 32 个字符

在没有连接的情况下调用 C++ Boost 异步服务器处理程序

c++ - 限制变量范围的优缺点

c++ - GLFW 编译 undefined reference

c++ - 停止通过 STL 容器调用重载的 new 和 delete 运算符

c++ - 在可变参数模板中使用声明