【问题标题】:How does C++ select which operator to use in if (class)?C++ 如何选择在 if (class) 中使用哪个运算符?
【发布时间】:2017-09-15 16:08:02
【问题描述】:

我有一个模仿整数行为的类。它有以下重载:

class myInt
{
    ...
    operator int() const { return val; }
    operator bool() const { return 0 != val; }
    operator myInt *() { assert(0); return NULL; } // Cast to pointer not supported
    ...
private:
    int val;
}

当我如下使用它时:

myInt i = 0;
if (i) ...

它命中了指针转换中的断言。

为什么 C++ 选择 this 而不是 if 中的 bool 运算符?

干杯,

伊恩

【问题讨论】:

    标签: c++ class if-statement boolean operator-overloading


    【解决方案1】:

    经过进一步调查,结果发现运算符 bool 上的 const 是问题所在。

    编译器更喜欢非常量运算符 myInt *() 而不是运算符 bool() const。

    当我添加以下重载时:

    operator bool() { return 0 != val; }
    

    代码根据需要进入了 bool 运算符。

    【讨论】:

    • 反之亦然:const 在指针转换上的缺乏是问题所在。这些函数都不会修改对象,所以它们都应该被标记为const
    • 重点是非 const 转换为指针优于 const 转换为 bool,即使它希望将类型视为布尔值。
    • 是的,没错。非常量运算符被应用于非常量对象,因为它是一个更好的匹配。如果所有转换运算符都是 const 就不会发生。
    猜你喜欢
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 2020-10-24
    • 2017-12-05
    • 2023-03-23
    • 2012-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多