如何确保二元布尔操作员正确处理其论点的构造

How to ensure binary boolean operators handle const-ness of their arguments correctly?

本文关键字:正确处理 操作员 二元 何确保 确保 布尔      更新时间:2023-10-16

我正在学习C ,我有问题理解为什么我会遇到以下错误:

mst.cpp:27:15: note:   no known conversion for implicit ‘this’ parameter from ‘const State*’ to ‘State*’

与代码相关的是

class State {
  size_t _node;
  double _dist;
public:
  State( size_t aNode, double aDist ) : _node{aNode}, _dist{aDist} {}
  inline size_t node() const { return _node; }
  inline double dist() const { return _dist; }
  inline bool operator< ( const State& rhs ) { return _dist < rhs.dist(); }
};

,而有问题的行(27)是此类声明的最后一行。为什么代码尝试执行从const到非CONST State*的转换?鉴于我们没有试图改变任何东西,他们是否应该被对待。另外,鉴于宪法性显然很重要,确保该示例可根据需要起作用而没有该错误的最佳方法是什么?

这是我的心理猜测:您正在使用Microsoft Visual Studio,并向我们展示了"错误窗口"中的错误。转到查看 ->输出以查看完整的编译器输出,该输出应该具有数百行的血腥详细信息。

继续猜测模式,您将这些State对象存储在set中,或者您可能是sort。无论您在做什么,都试图使用两个const对象使用operator<。不幸的是:

inline bool operator< ( const State& rhs )        { return _dist < rhs.dist(); }
                                          ^^^^^^^^

仅当左侧不是const时,operator<才能调用。添加我标记的const,这应该解决问题。为了避免此问题,出于其他整洁的原因,声明布尔函数的正常方法是通过朋友函数(仍然在同类中):

friend bool operator<( const State& lhs, const State& rhs )
{ return lhs.dist() < rhs.dist(); }

由于该函数是在类中定义的,因此在此不需要inline关键字,或您列出的任何功能。