【问题标题】:C++ overloading operator< errorC ++重载运算符<错误
【发布时间】:2012-12-18 14:05:30
【问题描述】:

当我没有将const 放入函数bool operator&lt;(const Node&amp; otherNode) //const 时,为什么会收到错误消息?

stl_algo.h:91: error: passing 'const Node' as 'this' argument of 'bool Node::operator<(const Node&)' discards qualifiers

所有重载的运算符都应该是常量吗?

class Node {
public:
    double coordinate;

    bool operator==(const Node& other) const{
        return coordinate == other.coordinate;
    }

    bool operator<(const Node& other) const{
        return coordinate < other.coordinate;
    }
};

【问题讨论】:

    标签: c++ operator-overloading constants


    【解决方案1】:

    不是所有的操作符,但==&lt; 绝对应该设为const,是的。从逻辑上讲,它们不会修改任何被比较的对象。

    错误可能来自于从const 调用非const 方法,例如:

    bool isSmaller(const Node& other) const
    {
       return *this < other;
    }
    

    在这种情况下,由于方法 isSmallerconstthis 隐含地是 const 对象,因此 operator &lt; 也必须是 const 以便在该上下文中调用有效。

    从错误消息来看,const 对象上似乎正在调用 Node::operator &lt;,来自 stl_algo.h 中的函数 - 排序/排序函数、散列函数等。

    【讨论】:

    • 是的,我正在做一个关于编程的测验,然后我因为比较重载运算符不起作用而感到恐慌,然后我只输入了 const 并且它起作用了,但我怀疑是否所有运算符都必须是常量。现在我明白了。谢谢。
    【解决方案2】:

    比较运算符,例如&lt;&gt;&lt;=&gt;===!= 通常应该对 const 对象进行操作,因为如果任何对象被比较可以通过比较来改变。但是您可以将比较声明为非成员函数,以确保两个操作数之间的对称性。

    class Node {
    public:
        double coordinate;
    };
    inline operator<(const Node& lhs, const Node& rhs)
    {
      return lhs.coordinate < rhs.coordinate;
    }
    

    【讨论】:

      【解决方案3】:

      您是否尝试删除方法的 const 修饰符?此外,正如@LuchianGrigore 所建议的,您可以使用this 关键字:

      bool operator< (const Node& other) {
          return this.coordinate < other.coordinate;
      }
      

      【讨论】:

      • 是的,如果我不输入const 我有错误,而如果我输入它,它可以正常工作。我只是想知道运算符是否应该都是 const 函数。
      • 我从来没有为此声明一个方法为 const。我不明白你为什么会收到这个错误。看看这个:cplusplus.com/doc/tutorial/classes2
      猜你喜欢
      • 2015-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-14
      • 2016-10-18
      • 1970-01-01
      相关资源
      最近更新 更多