2012-12-18 100 views
2

为什么我在功能bool operator<(const Node& otherNode) //const中没有放入const时收到错误?C++过载运算符<错误

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; 
    } 
}; 

回答

6

并非所有的运营商,但==<绝对应该做const,是的。它们逻辑上不会修改正在比较的任何一个对象。

误差可能来自从const一个调用非const方法,例如:

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

在这种情况下,由于该方法是isSmallerconstthis是隐式const对象,因此也operator <必须为const,以便该上下文内的调用有效。

从错误信息,看来Node::operator <被称为const对象上,从一个函数在​​- 排序/订购功能,散列函数等

+0

是我在编程测验,然后我慌了,因为比较超载运营商是不工作的话,我只是把常量,它工作,但我怀疑是否所有的操作符都必须是const。现在我明白了。谢谢。 – BRabbit27

1

比较运算符,如<><=,>=,==,!=应该在const对象上运行,因为如果任何被比较的对象可以通过比较而被改变,则这是没有意义的。但是您可以将比较声明为非成员函数,以确保两个操作数之间的对称性。

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

为什么downvote? – juanchopanza

0

您是否尝试删除方法的const修饰符?此外,作为@LuchianGrigore sugest,您可以使用关键字this

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

是的如果我不把'const'我有错误,而如果我把它,它能正常工作。我只是想知道运营商是否应该是所有const函数。 – BRabbit27

+0

我从来没有为const声明过一个方法。我不明白你为什么得到这个错误。看看这个:http://www.cplusplus.com/doc/tutorial/classes2/ – adripanico

+0

只要阅读@LuchianGrigore的答案 – BRabbit27