如何在c++类中重写bool操作符
How do I override the bool operator in a C++ class?
我正在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();
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 写入向量<向量<bool>>
- 将OpenCV C++重写为EmguCV C#-如何使用指针
- 在 C++ 中用派生类型重写成员函数
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 方法重写线程C++中的概念
- 为重写std::exception的库生成swig接口时出错
- 让bool方法返回其他整数
- 如何强制从重写方法调用重写的方法基方法?
- 用于C++的静态二进制检测或二进制重写工具和框架
- 如何将 if else 语句重写为 switch 语句
- 如何在 std::vector 中找到<bool>哪些索引是真的?
- 如何重写全局方法名称以在调用原始方法之前将我的代码推到前面
- Arduino-C++ bool 不会从 false 变为 true
- 用 C 重写C++类
- 为什么在这种情况下,bool 类型的输出等于 0?
- 显式 std::exception_ptr 转换为 bool 不存在.VS2010 错误?
- 是否总是可以将使用递归编写的程序重写为不使用递归的程序C++,性能观点是什么?
- 重写虚拟函数和继承
- 如何在c++类中重写bool操作符