IvanKeller

导航

cin作为判断语句的测试条件

while (cin)
{
    //代码
}
if (!cin)
{
  //代码
}

 

我是这样理解的:既然cin可以作为判断语句的测试条件,cin必须可以转换为特定类型(哪些类型可以作为判断语句的测试条件)?

https://docs.microsoft.com/zh-cn/cpp/cpp/while-statement-cpp?view=vs-2019

expression must be of an integral type, a pointer type, or a class type with an unambiguous conversion to an integral or pointer type.

https://docs.microsoft.com/zh-cn/cpp/cpp/if-else-statement-cpp?view=vs-2019

  • TRUE
  • a non-null pointer,
  • any non-zero arithmetic value, or
  • a class type that defines an unambiguous conversion to an arithmetic, boolean or pointer type. (For information about conversions, see Standard Conversions.)

在头文件中找找cin是何种类型,以及有哪些类型转换函数:

__PURE_APPDOMAIN_GLOBAL extern _CRTDATA2_IMPORT istream cin, *_Ptr_cin;  <iostream>头文件中,无任何类型转换函数

 

using istream = basic_istream<char, char_traits<char>>;  <iosfwd>头文件中,无任何类型转换函数

 

template<class _Elem,class _Traits>
class basic_istream : virtual public basic_ios<_Elem, _Traits>;  <istream>头文件中,

explicit __CLR_OR_THIS_CALL operator bool() const    //但是前面有explicit 修饰,不可用于隐式转换
{ // test if _Ipfx succeeded
  return (_Ok);
}

 

template<class _Elem,class _Traits>
class basic_ios : public ios_base;  <ios>头文件中,无任何类型转换函数

 

class _CRTIMP2_PURE_IMPORT ios_base : public _Iosb<int>;  <xiosbase>头文件中,

explicit __CLR_OR_THIS_CALL operator bool() const  //同样有explicit修饰
{ // test if no stream operation has failed
return (!fail());

}

_NODISCARD bool __CLR_OR_THIS_CALL operator!() const  //!运算符重载可以使用,但是文章开头测试条件并没有!运算符
{ // test if any stream operation has failed
return (fail());
}

 

template<class _Dummy>
class _Iosb;  <xiosbase>头文件中,无任何类型转换函数

 

综上,!cin 可以调用 ! 运算符重载函数 转换为可作为判断语句的测试条件 的类型,但是cin却没有可以用的(隐式)类型转换函数。但是实际上开头的两个都可以作为测试条件,是哪里出了问题?待续~

 

posted on 2019-05-16 11:05  IvanKeller  阅读(545)  评论(0)    收藏  举报