c++ convert class to boolean

前端 未结 5 1341
既然无缘
既然无缘 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:41

    C++ checks if the statements result is whether equal to zero nor not. So i think you can define equality operator for your class and define how your class will be different from zero in which conditions.

    0 讨论(0)
  • 2020-12-14 16:44

    As others have stated, using operator int () or operator bool () is bad idea because of the conversions it allows. Using a pointer is better idea. The best know solution to this problem so far is to return a member (function) pointer:

    class MyClass {
      void some_function () {}
    
      typedef void (MyClass:: * safe_bool_type) ();
      operator safe_bool_type () const
      { return cond ? &MyClass::some_function : 0; }
    };
    
    0 讨论(0)
  • 2020-12-14 16:49

    You can define a user-defined conversion operator. This must be a member function, e.g.:

    class MyClass {
      operator int() const
      { return your_number; }
      // other fields
    };
    

    You can also implement operator bool. However, I would STRONGLY suggest against doing it because your class will become usable in arithmetic expressions which can quickly lead to a mess. IOStreams define, for example, conversion to void*. You can test void* in the same way you can test a bool, but there are no language-defined implicit conversions from void*. Another alternative is to define operator! with the desired semantics.

    In short: defining conversion operator sto integer types (including booleans) is a REALLY bad idea.

    0 讨论(0)
  • 2020-12-14 16:54

    Simply implement operator bool() for your class.

    e.g.

    class Foo
    {
    public:
        Foo(int x) : m_x(x) { }
        operator bool() const { return (0 != m_x); }
    private:
        int m_x;
    }
    
    Foo a(1);
    if (a) { // evaluates true
        // ...
    }
    
    Foo b(-1);
    if (b) { // evaluates true
        // ...
    }
    
    Foo c(0);
    if (c) { // evaluates false
        // ...
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题