为什么我的"显式运算符bool()"没有被调用?

xml*_*lmx 7 c++ boolean type-conversion explicit-conversion c++11

#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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的期望是A()将在上下文中转换为bool使用my operator bool(),因此打印true.

但是,输出false显示已operator int()被调用.

为什么我explicit operator bool没有按预期召唤?

Tem*_*Rex 16

因为A()不是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;
    }
}
Run Code Online (Sandbox Code Playgroud)

打印的实例:"bool:true",没有const打印"int:false"

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

// operator int() without const

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

    if (a)
    // as before
}
Run Code Online (Sandbox Code Playgroud)

打印"bool:true"的实例.

  • @downvoter:请详细说明,以便我可以改进我的anwswer! (2认同)