下面的代码在 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
.
但在其他不是条件的语句(if
、while
、...)中,显式转换运算符不参与重载决议,并且那么唯一有效的操作符是operator void*
,可以使用它是因为存在从指针到bool
的隐式转换。
如果您希望选择 operator bool
,则需要将其设为非explicit
,或使用强制转换(因为这是将其标记为 explicit
表示,确保必须明确使用它):
f(static_cast<bool>(a));
关于c++ - bool vs void* 对同一个对象进行强制转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45322138/