为什么istream对象可以用作bool表达式? [英] Why istream object can be used as a bool expression?

查看:237
本文介绍了为什么istream对象可以用作bool表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人知道为什么istream对象可以用作bool表达式?例如:

Does anyone know why istream object can be used as bool expression? For example:

ifstream input("tmp");
int iValue;
while (input >> iValue)
    //do something;

这里输入> iValue 返回对ifstream对象的引用。我想知道为什么这个对象可以用作一个bool表达式。

我查看ifstream类,发现这可能是由于以下成员函数:

Here input >> iValue returns a reference to the ifstream object. I want to know why this object can be used as a bool expression.
I look into the ifstream class and find that this may be due to the following member function:

operator void * ( ) const;

请参阅这里有关此函数的详细信息。

如果是,任何人都可以向我解释这个函数?这个函数的原型不同于通常的运算符过载声明。这个函数的返回类型是什么?

如果不是,那么ifstream对象可以用作bool表达式的原因是什么?

期待您的帮助!

See here for detail about this function.
If it is, can anyone explain this function to me? The prototype of this function is different from usual operator overload declaration. What is the return type of this function?
If it is not, then what is the reason that ifstream object can be used as bool expression?
Looking forward to your help!

cheng

推荐答案

使用istream作为布尔表达式的确切机制在C + +11。以前是一个隐式转换为 void * ,如你所发现的。在C ++ 11中,它是显式转换为 bool

The exact mechanism that enables use of an istream as a boolean expression, was changed in C++11. Previously is was an implicit conversion to void*, as you've found. In C++11 it is instead an explicit conversion to bool.

启用在布尔表达式中使用istream或ostream,以便C ++程序员可以继续使用具有副作用的表达式作为的条件 for loop:

Use of an istream or ostream in a boolean expression was enabled so that C++ programmers could continue to use an expression with side-effects as the condition of a while or for loop:

SomeType v;

while( stream >> v )
{
    // ...
}

程序员这么做,想要的原因是,它提供了更简洁的代码,代码更容易一目了然,比如…

And the reason that programmers do that and want that, is that it gives more concise code, code that is easier to take in at a glance, than e.g. …

for( ;; )
{
    SomeType v;

    stream >> v;
    if( stream.fail() )
    {
        break;
    }
    // ...
}

在一些情况下甚至可以优选这种详细结构。这取决于。

However, in some cases even such a verbose structure can be preferable. It depends.

干杯& hth。,

Cheers & hth.,

这篇关于为什么istream对象可以用作bool表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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