9
#include <iostream>

using namespace std;

struct A
{
    explicit operator bool() const
    {
        return true;
    }

    operator int()
    {
        return 0;
    }
};

int main()
{
    if (A())
    {
        cout << "true" << endl;
    }
    else
    {
        cout << "false" << endl;
    }
}

我的期望是A()根据上下文转换为bool使用 my operator bool(),因此 print true

但是,输出是false,表明它operator int()被调用了。

为什么我explicit operator bool没有按预期调用?

4

1 回答 1

18

因为A()is not const,所以operator int()被选中。只需添加const到另一个转换运算符,它就可以工作:

#include <iostream>

using namespace std;

struct A
{
    explicit operator bool() const
    {
        std::cout << "bool: ";
        return true;
    }

    operator int() const
    {
        std::cout << "int: ";
        return 0;
    }
};

int main()
{
    if (A())
    {
        cout << "true" << endl;
    }
    else
    {
        cout << "false" << endl;
    }
}

打印的实时示例:“bool:true”,没有const它打印“int:false”

或者,创建一个命名常量:

// operator int() without const

int main()
{
    auto const a = A();

    if (a)
    // as before
}

打印“bool:true”的实时示例

于 2014-06-30T12:08:38.470 回答