我的意思是,我们都知道有否定逻辑运算符!
,它可以这样使用:
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()
它本身就很危险,我们通常使用一种叫做safe-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;
}
};
在 C++11 中,我们得到显式转换运算符;因此,上述成语已过时:
class X{
bool internal_test() const;
public:
explicit operator bool() const{
return internal_test();
}
};
operator bool() { //implementation };