BRa*_*t27 2 c++ const operator-overloading
为什么我在没有const输入功能时收到错误bool operator<(const Node& otherNode) //const?
stl_algo.h:91: error: passing 'const Node' as 'this' argument of 'bool Node::operator<(const Node&)' discards qualifiers
Run Code Online (Sandbox Code Playgroud)
所有重载运算符都应该是常量吗?
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;
}
};
Run Code Online (Sandbox Code Playgroud)
并非所有的运营商,但==并<一定要进行const的,是的.它们逻辑上不会修改任何被比较的对象.
该错误可能来自于const从一个调用非方法const,例如:
bool isSmaller(const Node& other) const
{
return *this < other;
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,由于该方法isSmaller是const,this隐式一个const对象,因此operator <也必须const以使该范畴内呼叫是有效的.
从错误消息中,它似乎Node::operator <是在一个const对象上调用,来自函数stl_algo.h- 排序/排序函数,散列函数等.