C ++:如何在条件表达式中将istream转换为bool [英] C++: how is istream is converted to bool inside a conditional expression

查看:314
本文介绍了C ++:如何在条件表达式中将istream转换为bool的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



例如,

  istream& operator>> (bool& val); 

但是当istream在条件语句中使用时如何转换为bool。 p>

例如,

  ifstream ifs //打开文件
istream& is =(istream&)ifs;

char c;

if(is>> c)//如何将istream计算为bool
{
//字符读取
}

任何人都可以解释在条件表达式中如何将它转换为bool?

解决方案

cppreference


  explicit std :: basic_ios :: operator bool 

如果流没有发生错误并且可以进行I / O操作,则返回true。具体来说,返回!fail()


一个布尔上下文,它将调用 std :: istream 的成员函数运算符。


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?

解决方案

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.

这篇关于C ++:如何在条件表达式中将istream转换为bool的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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