C++标准库笔记:13.4.3 Stream状态与布尔条件测试

来源:互联网 发布:旅行的意义 知乎 编辑:程序博客网 时间:2024/06/05 15:02

流条件测试

int a = 0;while( (std::cin >> a) ){    cout << a << endl;}

以上代码得以使用std::cin来做条件测试,是因为Stream在类ios_base内定义了两个可用于布尔表达式的函数,

__CLR_OR_THIS_CALL operator void *() const    {   // test if any stream operation has failed        return (fail() ? 0 : (void *)this);    }bool __CLR_OR_THIS_CALL operator!() const    {   // test if no stream operation has failed        return (fail());    }

以上有个疑惑,为什么要重载void*,而不直接重载bool呢?
原来是因为流对操作符<<和>>做了重载,如果重载operator bool()的话,此处就会出现bool << 和 bool >>的情况,这是一种移位操作,同流操作符<<和>>产生了二义性。因此标准库就只能退而求其次,重载operator void*代替operator bool了(这些都是站在c++98的基础上说的,c++11已经不一样了,具体可看此处)

operator !()使用注意事项

我们可以使用!操作符来对流进行测试,如下

int a = 0;do{    if ( !(cin >> a) )    {        break;    }    cout << a << endl;}while( true );

其中!操作符之后的小括号是必须的,因为!操作符的优先级高于 >>

使用建议

使用转换为布尔的方式,即使用operator void* 与operator !(),会引起编程风格的争论。通常,使用诸如fail()这样的有较佳可读性

阅读全文
0 0