首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C++重载operator<错误

C++重载operator<错误
EN

Stack Overflow用户
提问于 2012-12-18 22:05:30
回答 3查看 472关注 0票数 2

当我没有在函数bool operator<(const Node& otherNode) //const中放入const时,为什么我会收到一个错误

代码语言:javascript
运行
复制
stl_algo.h:91: error: passing 'const Node' as 'this' argument of 'bool Node::operator<(const Node&)' discards qualifiers

所有的重载操作符都应该是常量吗?

代码语言:javascript
运行
复制
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;
    }
};
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-12-18 22:06:45

不是所有的运算符,但==<绝对应该成为const,是的。从逻辑上讲,它们不修改被比较的任何一个对象。

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

代码语言:javascript
运行
复制
bool isSmaller(const Node& other) const
{
   return *this < other;
}

在本例中,由于方法isSmallerconst,因此this隐式地是一个const对象,因此operator <也必须为const才能使该上下文中的调用有效。

从错误消息中可以看出,Node::operator <是在const对象上、从stl_algo.h中的函数调用的-排序/排序函数、散列函数等。

票数 6
EN

Stack Overflow用户

发布于 2012-12-18 22:11:16

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

代码语言:javascript
运行
复制
class Node {
public:
    double coordinate;
};
inline operator<(const Node& lhs, const Node& rhs)
{
  return lhs.coordinate < rhs.coordinate;
}
票数 1
EN

Stack Overflow用户

发布于 2012-12-18 22:15:02

你有没有试过删除方法的常量修饰符?此外,作为@LuchianGrigore的建议,您可以使用this关键字:

代码语言:javascript
运行
复制
bool operator< (const Node& other) {
    return this.coordinate < other.coordinate;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13934690

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档