How do I override the bool operator in a C++ class?

后端 未结 4 1310
遇见更好的自我
遇见更好的自我 2020-12-09 10:31

I\'m defining a ReturnValue class in C++ that needs to report whether a method was successful. I want objects of the class to evaluate to true on s

4条回答
  •  感动是毒
    2020-12-09 11:17

    It's better to use explicit keyword or it will interfere with other overloads like operator+

    Here is an example :

    class test_string
    {
    public:
       std::string        p_str;
    
       explicit operator bool()                  
       { 
         return (p_str.size() ? true : false); 
       }
    };
    

    and the use :

    test_string s;
    
    printf("%s\n", (s) ? s.p_str.c_str() : "EMPTY");
    

提交回复
热议问题