为什么没有iostream对象重载operator bool? [英] Why don't iostream objects overload operator bool?

查看:228
本文介绍了为什么没有iostream对象重载operator bool?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此答案中我讨论使用 std :: ifstream 对象转换为 bool 来测试流是否仍处于良好状态。我在Josuttis的书中查看了更多的信息(如果你感兴趣的话,第600页),事实证明 iostream 对象实际上重载 void * 。当流错误(可以隐式转换为 false )时返回空指针,否则返回非空指针(隐式转换为 true )。为什么他们只是重载 operator bool

In this answer I talk about using a std::ifstream object's conversion to bool to test whether the stream is still in a good state. I looked in the Josuttis book for more information (p. 600 if you're interested), and it turns out that the iostream objects actually overload operator void*. It returns a null pointer when the stream is bad (which can be implicitly converted to false), and a non-null pointer otherwise (implicitly converted to true). Why don't they just overload operator bool?

推荐答案

一个安全bool问题的实例。

This is an instance of the "safe bool" problem.

这里是一篇好文章: http://www.artima.com/cppsource/safebool.html

C ++ 0x可帮助 explicit 转换函数,以及Kristo提到的更改。另请参见安全的成语是否过时?

C++0x helps the situation with explicit conversion functions, as well as the change that Kristo mentions. See also Is the safe-bool idiom obsolete? .

这篇关于为什么没有iostream对象重载operator bool?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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