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()ではないのでconstoperator 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 に答える