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

拈花ヽ惹草 提交于 2019-12-17 18:52:51

问题


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 success and false on error. Which operator do I override to control the truthiness of my class?


回答1:


The simple answer is providing operator bool() const, but you might want to look into the safe bool idiom, where instead of converting to bool (which might in turn be implicitly converted to other integral types) you convert to a different type (pointer to a member function of a private type) that will not accept those conversions.




回答2:


Well, you could overload operator bool():

class ReturnValue
{
    operator bool() const
    {
        return true; // Or false!
    }
};



回答3:


overload this operator:

operator bool();



回答4:


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");


来源:https://stackoverflow.com/questions/5829487/how-do-i-override-the-bool-operator-in-a-c-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!