在我的C++编程中,我已经使用了相当多的语句:
std::string s;
std::ifstream in("my_input.txt");
if(!in) {
std::cerr << "File not opened" << std::endl;
exit(1);
}
while(in >> s) {
// Do something with s
}
Run Code Online (Sandbox Code Playgroud)
我想知道的是,为什么这有效?
我查看了返回值operator>>,它是一个istream对象,而不是布尔值.如何将istream对象解释为可以放在if语句和while循环中的bool值?
基类std::basic_ios提供了一个operator bool()返回表示流的有效性的布尔值的方法.例如,如果读取到达文件末尾而没有抓取任何字符,则将std::ios_base::failbit在流中设置.然后operator bool()将调用,返回!fail(),此时提取将停止,因为条件为false.
条件表达式表示显式布尔转换,因此:
while (in >> s)
Run Code Online (Sandbox Code Playgroud)
相当于此
while (static_cast<bool>(in >> s))
Run Code Online (Sandbox Code Playgroud)
这相当于此
while ((in >> s).operator bool())
Run Code Online (Sandbox Code Playgroud)
这相当于
while (!(in >> s).fail())
Run Code Online (Sandbox Code Playgroud)
std::basic_ios输入和输出流从中继承,具有转换功能operator bool(或者operator void*在C++ 11之前解决安全bool问题,由于explicit关键字,这不再是问题).