0
点赞
收藏
分享

微信扫一扫

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

凉夜lrs 2022-12-07 阅读 136


流条件测试

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 条评论