C++: how is istream is converted to bool inside a conditional expression [duplicate]

不羁的心 提交于 2019-12-06 14:21:32

问题


The istream operator>> is used to read the data and the function returns reference to istream.

For example,

istream& operator>> (bool& val);

But how does the istream is converted into a bool when it is used inside the conditional statement.

For example,

ifstream ifs(.....);  // open the file
istream &is = (istream&)ifs;

char c;

if(is >> c)   // how the istream is been evaluated into as bool
{
    // character read
}

Can anyone explain how it is being converted into a bool inside a conditional expression?


回答1:


From cppreference:

   explicit std::basic_ios::operator bool() const;

Returns true if the stream has no errors occurred and is ready of I/O operations. Specifically, returns !fail().

So since an if statement is a boolean context, it will invoke std::istream's member function operator.




回答2:


operator >> return a reference to istream (istream&).

and so you're actually writing if (istream) which is in turn calling the operator bool..

in conditionals 0 is false anything else is true -> istream has an opeartor bool that checks if the stream is ok so it will return !fail()...hence true.



来源:https://stackoverflow.com/questions/16777451/c-how-is-istream-is-converted-to-bool-inside-a-conditional-expression

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!