1. 程式人生 > >C++中cin,cout,以及返回值

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

///

  1. 檔案   bits/basic_ios.h     
  2. ....     
  3.         public:     
  4.             operator   void*()   const
  5.             {   returnthis->fail()   ?   0   :   const_cast<basic_ios*>(this);   }     
  6.             bool
  7.             operator!()   const
  8.             {   returnthis->fail();   }     
  9. ....