while(cin>>something)

本文解析了C++中如何使用cin>>a作为条件表达式进行文件结束判断。详细解释了basic_istream类及其转换运算符如何实现这一功能,并附带了解释性注释。

经常在判断输入文件是否结束时用到这样的代码:
   

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语句就不能通过。
    迷题解开了。

转载自:http://yuhuafx.blog.hexun.com/32067084_d.html

已知LinkList类部分代码如下(勿改动),请实现函数InsertR,InsertF,DispList和AddDx,达到对应的输出。 //头结点 template <class T&gt; struct Node { T data; Node<T&gt; *next; }; template <class T&gt; class LinkList { public: LinkList(); //建立只有头结点的空链表 ~LinkList(); //析构函数 void InsertR(T x); //在链表的表尾位置插入元素值为x的结点 void InsertF(T x); //在链表的头结点后插入元素值为x的结点 void DispList(); //遍历链表,依次输出各元素 void AddDx(int dx); //将表中不是3的倍数的元素值增dx,其它值不变 private: Node<T&gt; *first; //单链表的头指针 }; //构造只有头结点的空表 template <class T&gt; LinkList<T&gt;:: LinkList( ){ first=new Node<T&gt;; first-&gt;next=NULL; } //析构 template <class T&gt; LinkList<T&gt;:: ~LinkList( ){ Node<T&gt; *s; while (first){ s=first; first=first-&gt;next; delete s; } } int main( ){ LinkList<int&gt; A; int x; while(1) { cin&gt;&gt;x; //输入整数 if(!x)break; //为0退出 A.InsertR(x); //表尾插入 } A.DispList(); int dx; cin&gt;&gt;dx; //输入dx A.AddDx(dx); A.DispList(); LinkList<char&gt; B; char ch; int n; cin&gt;&gt;n; //输入个数n for(int i=1;i<=n;i++) { cin&gt;&gt;ch; //输入n个字符 B.InsertF(ch); //表头后插入 } B.DispList(); return 0; } 输出 每个输出数据之间用1个空格隔开,每次链表遍历结束需换行 样例输入 Copy 1 2 42 2 3 12 23 0 5 6 ASDFGH 样例输出 Copy Data:1 2 42 2 3 12 23 Data:6 7 42 7 3 12 28 Data:H G F D S A用java做
03-25
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值