为什么我的"显式运算符bool()"不叫?

时间:2014-06-30 12:05:18

标签: c++ c++11 boolean type-conversion explicit-conversion

#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从上下文转换为operator bool(),因此请打印true

但是,输出为false,表示调用了operator int()

为什么我的explicit operator bool未按预期调用?

1 个答案:

答案 0 :(得分: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;
    }
}

Live Example打印:“bool:true”而没有const打印“int:false”

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

// operator int() without const

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

    if (a)
    // as before
}
打印“bool:true”的

Live Example

相关问题