#include
using std::cin;
using std::cout;
int main()
{
int i;
cin>>i;
if(cin) //cin是如何知道你输入的是否符合i的类型
cout< else
cout< return 0;
}
cin是istream对象,istream继承自ios,ios继承自ios_base。不要忘记C++的类型转换,可以隐式的向上类型转换,一个类的类型也可以转换成需要的简单类型(类中定义转换简单类型的函数),需要的时候编译器会知道调用他,条件判断无非是bool类型或者可以转化成bool类型的类型。
basic_ios里面定义了一个成员函数,可以转化成void*指针,void*指针可以转化成bool类型,if(cin)调用过程就是调用这个函数operator void *() const;
如果if(!cin)则是调用另外一个成员函数bool operator !() const;
如果你问cin为何能识别输入类型,那是靠重载>>来识别的。
下面的是关于>>的重载成员函数:
istream& operator>> (bool& val );
istream& operator>> (short& val );
istream& operator>> (unsigned short& val );
istream& operator>> (int& val );
istream& operator>> (unsigned int& val );
istream& operator>> (long& val );
istream& operator>> (unsigned long& val );
istream& operator>> (float& val );
istream& operator>> (double& val );
istream& operator>> (long double& val );
istream& operator>> (void*& val );
istream& operator>> (streambuf* sb );
istream& operator>> (istream& ( *pf )(istream&));
istream& operator>> (ios& ( *pf )(ios&));
istream& operator>> (ios_base& ( *pf )(ios_base&));
下面的不是成员函数,而是全局函数:
istream& operator>> (istream& is, char& ch );
istream& operator>> (istream& is, signed char& ch );
istream& operator>> (istream& is, unsigned char& ch );
istream& operator>> (istream& is, char* str );
istream& operator>> (istream& is, signed char* str );
istream& operator>> (istream& is, unsigned char* str );
using std::cin;
using std::cout;
int main()
{
int i;
cin>>i;
if(cin) //cin是如何知道你输入的是否符合i的类型
cout< else
cout< return 0;
}
cin是istream对象,istream继承自ios,ios继承自ios_base。不要忘记C++的类型转换,可以隐式的向上类型转换,一个类的类型也可以转换成需要的简单类型(类中定义转换简单类型的函数),需要的时候编译器会知道调用他,条件判断无非是bool类型或者可以转化成bool类型的类型。
basic_ios里面定义了一个成员函数,可以转化成void*指针,void*指针可以转化成bool类型,if(cin)调用过程就是调用这个函数operator void *() const;
如果if(!cin)则是调用另外一个成员函数bool operator !() const;
如果你问cin为何能识别输入类型,那是靠重载>>来识别的。
下面的是关于>>的重载成员函数:
istream& operator>> (bool& val );
istream& operator>> (short& val );
istream& operator>> (unsigned short& val );
istream& operator>> (int& val );
istream& operator>> (unsigned int& val );
istream& operator>> (long& val );
istream& operator>> (unsigned long& val );
istream& operator>> (float& val );
istream& operator>> (double& val );
istream& operator>> (long double& val );
istream& operator>> (void*& val );
istream& operator>> (streambuf* sb );
istream& operator>> (istream& ( *pf )(istream&));
istream& operator>> (ios& ( *pf )(ios&));
istream& operator>> (ios_base& ( *pf )(ios_base&));
下面的不是成员函数,而是全局函数:
istream& operator>> (istream& is, char& ch );
istream& operator>> (istream& is, signed char& ch );
istream& operator>> (istream& is, unsigned char& ch );
istream& operator>> (istream& is, char* str );
istream& operator>> (istream& is, signed char* str );
istream& operator>> (istream& is, unsigned char* str );
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/10697500/viewspace-530082/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/10697500/viewspace-530082/