关于cout cin的返回值
2012-03-18 16:51
351 查看
cin,cout,以及其返回值
Posted on 2011-06-09 10:19 tianya10319 阅读(204) 评论(0) 编辑 收藏今天在看c++primer的时候,读到其中这样一段话:
When we use an istream as a condition, the effect is to test the state of the stream. If the stream is validthat is, if it is still possible to read another input then the test succeeds. An istream becomes invalid when we hit end-of-file or encounter an invalid input, such as reading a value that is not an integer. An istream that is in an invalid state will cause the condition to fail.
其对应代码是:while (std::cin >> value)
...
开始就觉得这样有点不对劲,但是也不知道是哪里不对劲.仔细一想,原来是觉得这个cin的位置十分诡异...
原来我们最常用的就是直接输入或者直接输出.比如cin>>value;或者cout<<value;现在把这个放到while里面进行判断.
难道cin与cout的返回值是bool型的?好像也说不过去.
GOOGLE之~~
分下面几点来说明:
1.cin和cout是iostream类的2个对象,而对象是无所谓返回值的.有返回值的是<<还有>>这2个操作符.由于我们知道,操作符其实也就是函数(在操作符重载的时候可以清晰的认识到).而>>操作符返回的是它的左操作数(left-operand).对于cin>>value;返回左操作数就是操作的流的引用,也就是istream&.
2.但是好像还是不对,因为while里面判断的是bool值,难道还能判断istream&吗?
打开<ISTREAM>头文件,找到类模板basic_istream的定义,摘出这么两个语来:
typedef basic_istream<_E, _Tr> _Myt;
_Myt& operator>>(......) ......
这说明cin >>的返回值类型就是basic_istream&,可是放到while()中情况又该是怎样的。while()中要求是布尔表达式,难不成basic_istream&类型可以转换成bool类型?继续查看头文件,发现所有的operator重载函数都是<<和>>,没有找到用于类型转换的操作那就只好追溯到父类basic_ios了。
打开头文件<IOS.H>,找到ios的定义,其中有这么一条语句,类型转换函数的定义:
operator void *() const { if(state&(badbit|failbit) ) return 0; return (void this; }
有这个函数的定义之后,编译器会在需要的情况下将ios类型自动转换为void*类型。因此,在表达式while (cin >> m >> n)中,括号中的表达式为了匹配bool类型将自动转换为void*类型。如果读入时发生错误返回0,否则返回cin的地址。
\\\
故能够放入while中判断.
view plaincopy to clipboardprint?
文件 bits/basic_ios.h
....
public:
operator void*() const
{ return this->fail() ? 0 : const_cast<basic_ios*>(this); }
bool
operator!() const
{ return this->fail(); }
....
转载:http://blog.csdn.net/kongbai308416350/archive/2009/08/21/4470914.aspx
istream和ostream类型也依靠转换函数,这使我们可以写下面这类语句:
while(cin>>x)cout<<x;
输入操作cin>>x返回istream&,这个值将被隐式转换到一个表明cin状态的值,而这个值将由while检测。当然,通常定义这样的转换并不是一个好主义,以这种方式从一个类型隐式转换到另一个,并在转换中丢失了信息。
以上摘自<The C++ Programing Lauguage>中文特别版。
相关文章推荐
- 关于Qt无法直接使用cout和cin的问题
- 关于Qt无法直接使用cout和cin的问题
- 关于printf/scanf 与 cin/cout 输入输出的速度研究
- 关于cin的返回值
- 关于cin.width()和cout.width()
- 关于cin与cout
- 关于加速cin cout
- 关于vc2008与VC6.0中cout和cin的问题
- 最近写出一个bug,关于模块在注册时返回-1
- C++输入cout与输出cin
- 关于cin,和cin.getline()连用问题
- mybatis关于插入返回主键ID问题(mysql)
- 关于c++ cout输出顺序问题。
- cin,cout与scanf,printf的速度到底相差多少
- 关于file_get_contents返回为空或函数不可用的解决方案
- 关于try和finally执行到的返回结果
- 关于ajax获取数据时候的返回
- 浅谈c++中的cin与cout
- 关于weblogic下使用URL.openConnection获取连接返回javax.net.ssl.SSLKeyException错误
- NYOJ 685 查找字符串 字典树 map容器 吐血经验 cin cout 与printf scanf