本文介绍了为什么我的“显式运算符 bool()"不叫?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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() 将使用我的 operator bool() 在上下文中转换为 bool,因此打印 真的.

My expectation was that A() would be contextually converted to bool using my operator bool(), and therefore print true.

然而,输出为 false,表明调用的是 operator int().

However, the output is false, showing that operator int() was invoked instead.

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

Why is my explicit operator bool not called as expected?

推荐答案

因为 A() 不是 constoperator int()> 被选中.只需将 const 添加到另一个转换运算符即可:

Because A() is not const, the operator int() is selected. Just add const to the other conversion operator and it works:

#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"

Live Example that prints: "bool: true" and without the const it prints "int: false"

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

Alternatively, make a named constant:

// operator int() without const

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

    if (a)
    // as before
}

实时示例,打印bool: true".

Live Example that prints "bool: true".

这篇关于为什么我的“显式运算符 bool()"不叫?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-10 23:29