c++ convert class to boolean

前端 未结 5 1343
既然无缘
既然无缘 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: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
        // ...
    }
    

提交回复
热议问题