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()自体はかなり危険なので、通常、セーフブールイディオムと呼ばれるものを使用します。

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 に答える