c++ - bool vs void* 对同一个对象进行强制转换

标签 c++ c++11 casting

下面的代码在 if 语句中使用时会打印“operator bool”,而在函数调用需要 bool 时会打印“operator void*”。

为什么不使用 operator bool 进行函数调用呢?以及如何让它在这两种情况下都使用它?

#include <iostream>

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

    operator void*() const
    {
        std::cout << "operator void*" << std::endl;
        return 0;
    }
};

void f(bool valid)
{
    std::cout << "f called " << valid << std::endl;
}

int main(int argc, char *argv[])
{
    A a;

    if(a)
        std::cout << "if a" << std::endl;

    f(a);

    return 0;
}

最佳答案

if 语句中,会考虑隐式和显式转换运算符。因为 A 有一个 operator bool,它会选择那个,因为它比将 A 转换为 void*< 更好 然后将其转换为 bool.

但在其他不是条件的语句(ifwhile、...)中,显式转换运算符不参与重载决议,并且那么唯一有效的操作符是operator void*,可以使用它是因为存在从指针到bool的隐式转换。

如果您希望选择 operator bool,则需要将其设为非explicit,或使用强制转换(因为这是将其标记为 explicit 表示,确保必须明确使用它):

f(static_cast<bool>(a));

关于c++ - bool vs void* 对同一个对象进行强制转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45322138/

相关文章:

c++ - 将 std::weak_ptr 与 std::shared_ptr 一起用于阴影

c++ - 如何在没有显式强制转换的情况下将 C++ 枚举类枚举器用作 std::array 索引

c++ - 根据函数名匹配在运行时调用函数

c++ - DLL 函数名称限制 - 函数名称末尾的数字可以吗?

c++ - 如何实现最简单的 C++ 可调用对象包装器?

c++ - 为什么结果输出为1

c# - 使用 "generic value"将对象转换为 KeyValuePair?

c - 将字符串解析为 int 数组 - 收到警告 "makes pointer from integer without a cast"

c# - 2 个对象,完全相同(命名空间除外)c#

c++ - 在 C++ 中传递带有可变参数的函数指针作为参数