如何覆盖 C++ 类中的 bool 运算符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5829487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:56:53  来源:igfitidea点击:

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

c++operatorsoperator-overloading

提问by Josh Glover

I'm defining a ReturnValueclass in C++ that needs to report whether a method was successful. I want objects of the class to evaluate to trueon success and falseon error. Which operator do I override to control the truthiness of my class?

ReturnValue在 C++ 中定义了一个需要报告方法是否成功的类。我希望类的对象true对成功和false错误进行评估。我应该重写哪个运算符来控制我的类的真实性?

回答by David Rodríguez - dribeas

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.

简单的答案是提供operator bool() const,但您可能想查看安全 bool idiom,而不是转换为 bool (这可能会隐式转换为其他整数类型),而是转换为不同的类型(指向成员函数的指针)不接受这些转换的私有类型)。

回答by Oliver Charlesworth

Well, you could overload operator bool():

好吧,你可以重载operator bool()

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

回答by atoMerz

overload this operator:

重载这个运算符:

operator bool();

回答by Yannuth

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

最好使用显式关键字,否则会干扰其他重载,例如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");