c++ convert class to boolean

前端 未结 5 1351
既然无缘
既然无缘 2020-12-14 16:12

With all of the fundamental types of C++, one can simply query:

if(varname)

and the type is converted to a boolean for evaluation. Is there

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-14 16:55

    The C++11 approach is:

    struct Testable
      {
        explicit operator bool() const
          { return false; }
      };
    
    int main ()
      {
        Testable a, b;
        if (a)      { /* do something  */ }  // this is correct
        if (a == b) { /* do something  */ }  // compiler error
      }
    

    Note the explicit keyword which prevents the compiler from converting implicitly.

提交回复
热议问题