如何覆盖 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
How do I override the bool operator in a C++ class?
提问by Josh Glover
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?
我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");