【问题标题】:operator << overloading often fails if operator is const?如果 operator 是 const,则 operator << 重载通常会失败?
【发布时间】:2015-12-13 03:29:53
【问题描述】:

如果我想重载&lt;&lt; 运算符以在类上使用cout,它应该如下所示:

template <typename coutT>
friend ostream& operator << (ostream &, const vector3D<coutT>&);

在课堂上,并且

template <typename coutT>
ostream& operator << (ostream & os,const vector3D<coutT>& v)
{
    os << "x: " << v.x<< "  y: " << v.y << "  z: " << v.z;
    return os; 
}

在外面。请注意第二个操作数的const。 这个代码示例工作得很好。现在解决问题。

如果我要使用字段的 getter 来编写重载函数,而不是直接寻址它们(因为 operator&lt;&lt;friend),我的编译器会抛出错误:

template <typename coutT>
ostream& operator << (ostream & os,const vector3D<coutT>& v)
{
   os << "x: " << v.getX() << "  y: " << v.getY()  << "  z: " << v.getZ();
   return os; 
}

错误:

(VisualStudio2012) errorC2662: "this-pointer cannot be convert from "const vector3D" in "vector3D&""

一个重要的注意事项是删除第二个操作数的“const”,这样它就像

 ostream& operator << (ostream & os,vector3D<coutT>& v){...}

结束编译器错误,但由于我不想更改v,它应该是一个常量。

我还应该提到,我认为这可能与一般的方法调用有关,但我不确定。


编辑: 所以解决了,将函数声明为 const 坚持 const 正确性。 错误消息以无法将 const 类型转换为非 const 类型的方式解释它。

顺便说一句。实际上我对快速响应印象深刻。

【问题讨论】:

  • getX等是如何声明的?
  • 确保getX()getY()getZ()const成员函数。
  • int getx(){return x;} 所以不要 const 你是对的
  • 参见template friends problem - 您的friend 声明存在问题。你在这个问题中描述的方式行不通。
  • 代码工作得很好,但我知道你的意思 M.M.最好将类的模板用于友元声明,因为它们每个只需要为一种类型工作,但这不是这里的主题。一定会调查的。

标签: c++ c++11 constants overloading ostream


【解决方案1】:

如果您想以这种方式使用 getter 函数,应将其声明为 const

例如

int getValue() const {
    return x;
}

完整示例:

#include <iostream>
#include <vector>

using namespace std;

class Foo {
    int x;
public:

    Foo(int a) : x(a) {
    }

    int getValue() const {
        return x;
    }

    friend ostream & operator<<(ostream & out, const Foo & foo) {
        return out << foo.getValue();
    }

};

int main() {

    vector<Foo> foo_vec = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

    for (vector<Foo>::iterator it = foo_vec.begin(); it != foo_vec.end(); it++) {
        cout << *it << ", ";
    }

    return 0;
}

【讨论】:

    【解决方案2】:

    你的问题是你没有标记get函数const

    它们需要看起来像这样:

    double getX() const;

    【讨论】:

      【解决方案3】:

      你需要使访问函数const:

      struct V
      {
          int getX() const { /* ... */ }
                     ^^^^^
      };
      

      只有const 成员函数可以在常量对象值上调用。反过来, const 成员函数不能改变对象。因此,常量正确性保证了常量值不能通过调用它的任何成员函数来改变。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多