3

我的意思是,我们都知道有否定逻辑运算符!,它可以这样使用:

class Foo
{
public:
    bool operator!() { /* implementation */ }
};

int main()
{
    Foo f;
    if (!f)
        // Do Something
}

是否有任何运营商允许这样做:

if (f)
    // Do Something

我知道这可能并不重要,但只是想知道!

4

3 回答 3

7

如果你小心的话,你可以声明和定义operator bool()隐式转换为。bool

或写:

if (!!f)
   // Do something
于 2012-01-21T17:54:29.230 回答
3

因为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();
  }
};
于 2012-01-21T18:14:09.103 回答
2
operator bool() { //implementation };
于 2012-01-21T17:57:10.553 回答