先写个引用(google的,我看书看不这么仔细,^-^)
Eckel/Allison's "Thinking in C++ Volume Two: Practical Programming" (the footnote on page 167):
"It is customary to use operator void *() in preference to operator bool()
because the implicit conversions from bool to int may cause surprises,
should you incorrectly place a stream in a context where an integer
conversion can be applied. The operator void*() function will only be
called implicitly in the body of a Boolean expression."
<1>
先简单说说 if(cin) while(cin)的用法:
1。cin 流对象,有标志位,当流输入有问题的时候,标志位就会on/off
2。cin 有成员函数,返回标志位的状态,比如cin.fail(), 如果输入流有问题,就会根据标志位返回 true
3。cin 有个重载操作符 ios::operator void* ,在布尔表达式中,流对象cin会调用该重载,把流对象隐式转换为指针。当cin.fail返回true的时候, 转换为NULL指针。
例子:
int v1,v2;
cin>>v1>>v2;
如果输入 1 g (回车),
g 不是数字,为不正确输入,输入流出错,cin.fail 值为true,此时,
if(cin) 中,cin 被转为NULL指针,不执行条件语句块
同样,while(cin)结束循环
<2>
那么,while(cin>>x)又如何呢?
流对象中,>>是重载操作符,它的返回值是流对象本身的引用。所以
while(cin>>x) 同下面两句
cin>>x;
while(cin);
是等效的。
-------
以上。