如何在c++类中重写bool操作符

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

本文关键字:重写 bool 操作符 c++      更新时间:2023-10-16

我正在c++中定义一个ReturnValue类,它需要报告一个方法是否成功。我希望类的对象在成功时评估为true,在错误时评估为false。我应该重写哪个操作符来控制类的真实性?

简单的答案是提供operator bool() const,但是您可能想要查看安全bool习惯用法,其中不是转换为bool(可能反过来隐式转换为其他整型),而是转换为另一种类型(指向私有类型成员函数的指针),该类型不接受这些转换。

你可以重载operator bool():

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

最好使用显式关键字,否则会干扰其他重载,如operator+

下面是一个例子:

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

的使用
test_string s;
printf("%sn", (s) ? s.p_str.c_str() : "EMPTY");

重载此操作符:

operator bool();