当我没有在函数bool operator<(const Node& otherNode) //const
中放入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;
}
};
发布于 2012-12-18 22:06:45
不是所有的运算符,但==
和<
绝对应该成为const
,是的。从逻辑上讲,它们不修改被比较的任何一个对象。
错误可能来自于从const
方法调用非const
方法,例如:
bool isSmaller(const Node& other) const
{
return *this < other;
}
在本例中,由于方法isSmaller
为const
,因此this
隐式地是一个const
对象,因此operator <
也必须为const
才能使该上下文中的调用有效。
从错误消息中可以看出,Node::operator <
是在const
对象上、从stl_algo.h
中的函数调用的-排序/排序函数、散列函数等。
发布于 2012-12-18 22:11:16
比较运算符(如<
、>
、<=
、>=
、==
、!=
)通常应对const
对象进行操作,因为如果通过比较可以更改任何被比较的对象,则没有任何意义。但您可以将比较声明为非成员函数,以确保两个操作数之间的对称性。
class Node {
public:
double coordinate;
};
inline operator<(const Node& lhs, const Node& rhs)
{
return lhs.coordinate < rhs.coordinate;
}
发布于 2012-12-18 22:15:02
你有没有试过删除方法的常量修饰符?此外,作为@LuchianGrigore的建议,您可以使用this
关键字:
bool operator< (const Node& other) {
return this.coordinate < other.coordinate;
}
https://stackoverflow.com/questions/13934690
复制相似问题