【问题标题】: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&lt;&lt;() 不适用于 const 对象,因为您已将其声明为

friend ostream& operator<<(ostream& os,T& t)

您需要告诉编译器您希望能够将其与const 对象一起使用:

friend ostream& operator<<(ostream& os, const T& t)

【讨论】:

  • @Benjamin 感谢您修正我的粗手指错字。
【解决方案2】:

您的operator&lt;&lt; 通常应通过const 引用来获取其参数:

friend ostream& operator<<(ostream& os, const T& t)

const 引用不能绑定到const 对象。这是有道理的,否则您可以通过引用修改const 对象。

【讨论】:

    【解决方案3】:

    只需添加一个 const 就可以了:

    friend ostream&amp; operator&lt;&lt;(ostream&amp; os,const T&amp; t)

    【讨论】:

      【解决方案4】:

      T&amp; 设为const 引用:

      friend ostream& operator<<(ostream& os,T& t)
      

      这样就变成了:

      friend ostream& operator<<(ostream& os,const T& t)
      

      或者,去掉&amp;

      friend ostream& operator<<(ostream& os,T t)
      

      两者都会在您的代码中给出以下结果:

      Val : 2

      在控制台中。

      【讨论】:

      • 或将其设为const 参考。
      猜你喜欢
      • 1970-01-01
      • 2012-03-05
      • 2019-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-24
      • 2012-05-21
      相关资源
      最近更新 更多