关于cin能识别输入的数据类型(重载操作符&类型转换)

#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 );

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/10697500/viewspace-530082/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/10697500/viewspace-530082/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值