如何确保二元布尔操作员正确处理其论点的构造
How to ensure binary boolean operators handle const-ness of their arguments correctly?
我正在学习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
关键字,或您列出的任何功能。
相关文章:
- arm-none-eabi-g++ 不能使用 -flto 正确处理弱别名
- 如何避免 boost 的野兽body_limit错误并正确处理大消息
- 如何正确处理渲染大小为 >= 2B 的 utf-8 字符?
- 是否正确处理了此代码异常?
- 为什么 CSpinButtonCtrl 不能正确处理大于 1000 的数字?
- 自定义迭代器:如果 a 和 b 的行为不同,如何正确处理距离计算和相等比较
- 编译器在 C/C++ 中通过指针调用函数时如何正确处理 ABI
- 如何在 Python 3 中正确处理用于嵌入的字符串
- 如何正确处理OpenSSL错误(BIO)
- 为什么我的模板专业检查不足以正确处理相应的类型
- 在子类过程中正确处理WM_PASTE
- 如何正确处理此SFINAE
- 如何在 c++ 中正确处理常量字符*
- 如何在多线程程序中使用 boost::asio 正确处理 fork()
- 类的静态实例无法在程序退出时正确处理资源删除
- 正确处理字节对齐问题 - 通过UDP在16位嵌入式系统和32位桌面之间
- 超载&LT的正确方法;操作员
- 如何确保二元布尔操作员正确处理其论点的构造
- FSNF 无法正确处理字符串
- VS2010 未正确处理预处理器条件下的"includes"