cin / cout 的返回值,返回值?呵呵,對象哪裏有返回值?

cin,cout,以及其返回值

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的地址。

 

 

///

[cpp] view plain copy
  1. 文件   bits/basic_ios.h     
  2. ....     
  3.         public:     
  4.             operator   void*()   const       
  5.             {   return   this->fail()   ?   0   :   const_cast<basic_ios*>(this);   }     
  6.     
  7.             bool       
  8.             operator!()   const       
  9.             {   return   this->fail();   }     
  10. ....     

 

 

 

 

 

 

 

故能夠放入while中判斷.

 

 

待續....

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章