int a;
while (cin >> a) {
    do something;
}


    但是"cin >> a"为什么能作为一个条件表达式呢?
    cin是basic_istream类的一个对象,它的>>运算符会返回自身的引用。也就是说"cin >> a"的返回值就是cin。而basic_istream类的父类basic_ios类有一个转换运算符(conversion operator)可以把自己转换成void*型,其定义如下(来自C++标准库中的basic_ios.h文件):
 
/**
 *  @brief  The quick-and-easy status check.
 *
 *  This allows you to write constructs such as
 *  "if (!a_stream) ..." and "while (a_stream) ..."
*/
operator void*() const
{ return this->fail() ? 0 : const_cast<basic_ios*>(this); }

    看,人家注释里都写得很明白了吧。如果你把一个basic_ios类的对象(cin就是)放到if语句的括号里,它就会被转换成void*型。如果输入失败的话,就会得到一个空指针(也就是0),那么if语句就不能通过。
    迷题解开了。

相关文章:

  • 2021-07-31
  • 2021-11-20
  • 2022-12-23
  • 2022-12-23
  • 2021-08-21
  • 2021-11-12
  • 2021-05-07
  • 2021-09-24
猜你喜欢
  • 2021-11-28
  • 2021-07-09
  • 2021-08-15
  • 2022-12-23
  • 2021-06-09
  • 2022-12-23
相关资源
相似解决方案