如何覆盖C ++类中的bool运算符? [英] How do I override the bool operator in a C++ class?

查看:131
本文介绍了如何覆盖C ++类中的bool运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中定义一个 ReturnValue 类,需要报告方法是否成功。我希望该类的对象成功时评估为 true ,并在错误时评估 false

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?

推荐答案

简单的答案是提供运算符bool()const ,但您可能想查看 safe bool idiom em> ,而不是转换为bool(可能会隐式转换为其他整数类型),而是转换为不接受这些转换的不同类型(指向专用类型的成员函数的指针)。

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.

这篇关于如何覆盖C ++类中的bool运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆