"operator bool()const"是什么意思

Che*_*eng 78 c++ operators conversion-operator implicit-conversion

例如:

operator bool() const 
{ 
    return col != 0; 
}
Run Code Online (Sandbox Code Playgroud)

col是一个int.operator bool() const工作怎么样?

Jam*_*lis 126

表单的成员函数

operator TypeName()
Run Code Online (Sandbox Code Playgroud)

是转换运算符.它们允许使用类类型的对象,就好像它们是类型一样TypeName,当它们存在时,它们将被转换为TypeName使用转换函数.

在这种特殊情况下,operator bool()允许使用类类型的对象,就像它是a一样bool.例如,如果您有一个名为class类型的对象,则obj可以将其用作

if (obj)
Run Code Online (Sandbox Code Playgroud)

这将调用operator bool(),返回结果,并使用结果作为条件if.

应该注意的是,这operator bool()是一个非常糟糕的想法,你真的不应该使用它.有关它为什么不好以及解决问题的详细解释,请参阅"安全布尔成语".

(C++ 0x,即将推出的C++标准版本,增加了对显式转换运算符的支持.这些将允许您编写一个explicit operator bool()正常工作的安全,而无需跳过实现Safe Bool Idiom的环节.)

  • 因此,根据今天的最后一段,使用“显式运算符 bool()”是完全可以的。我理解正确吗? (2认同)
  • @JoeSteele - 请参阅 /sf/answers/1163100781/。显式转换运算符是安全的! (2认同)

小智 8

operator bool() const 
{
    return col != 0;
}
Run Code Online (Sandbox Code Playgroud)

定义类如何转换为布尔值,const()用于表示此方法不变异(更改此类的成员).

您通常会使用以下运算符:

airplaysdk sdkInstance;
if (sdkInstance) {
    std::cout << "Instance is active" << std::endl;
} else {
    std::cout << "Instance is in-active error!" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)


sel*_*oot 6

我想提供更多代码来说清楚.

struct A
{
    operator bool() const { return true; }
};

struct B
{
    explicit operator bool() const { return true; }
};

int main()
{
    A a1;
    if (a1) cout << "true" << endl; // OK: A::operator bool()
    bool na1 = a1; // OK: copy-initialization selects A::operator bool()
    bool na2 = static_cast<bool>(a1); // OK: static_cast performs direct-initialization

    B b1;     
    if (b1) cout << "true" << endl; // OK: B::operator bool()
    // bool nb1 = b1; // error: copy-initialization does not consider B::operator bool()
    bool nb2 = static_cast<bool>(b1); // OK: static_cast performs direct-initialization
}
Run Code Online (Sandbox Code Playgroud)