我们都知道有一个否定逻辑运算符!
,可以这样使用:
class Foo
{
public:
bool operator!() { /* implementation */ }
};
int main()
{
Foo f;
if (!f)
// Do Something
}
有没有任何运算符可以实现这个:
if (f)
// Do Something
我知道这可能不重要,但只是好奇!
我们都知道有一个否定逻辑运算符!
,可以这样使用:
class Foo
{
public:
bool operator!() { /* implementation */ }
};
int main()
{
Foo f;
if (!f)
// Do Something
}
有没有任何运算符可以实现这个:
if (f)
// Do Something
我知道这可能不重要,但只是好奇!
operator bool()
怎么不是直接的? - Lightness Races in Orbitif
需要其条件表达式为bool
类型,因此您提供的任何内容都将在可能的情况下转换为bool
。对于if (1)
也是同样的情况。 - Lightness Races in Orbit由于operator bool()
本身相当危险,我们通常使用一个叫做安全布尔Idiom的东西:
class X{
typedef void (X::*safe_bool)() const;
void safe_bool_true() const{}
bool internal_test() const;
public:
operator safe_bool() const{
if(internal_test())
return &X::safe_bool_true;
return 0;
}
};
class X{
bool internal_test() const;
public:
explicit operator bool() const{
return internal_test();
}
};
operator bool() { //implementation };