C++:在条件表达式中如何将istream转换为bool

5

istream的operator>>用于读取数据,并返回对istream的引用。

例如,

istream& operator>> (bool& val);

但是当 istream 在条件语句中使用时,它是如何转换为 bool 值的呢?

例如:

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
}

有人能解释一下在条件表达式中它是如何转换为布尔值的吗?

ifstream 是从 istream 派生的吗? - John
2个回答

10

来自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().

因为if语句是布尔上下文,所以它会调用std::istream的成员函数operator。


1
ifstream 是从 istream 派生而来的吗? - John
1
@John 是的,没错。 - David G

0

运算符 >> 返回一个 istream(istream&)的引用。

所以实际上你正在写 if (istream),这又调用了 operator bool..

在条件语句中,0 为假,任何其他值都为真 -> istream 有一个检查流是否正常的 operator bool,因此它将返回 !fail()... 因此为真。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接