2017-10-11 202 views
1

我正在C++的一個介紹級別課程上進行測驗,我試圖理解一個問題。在搜索了互聯網並沒有得到答案之後,我就在這裏。fstream,ofstream,ostream,iostream之間的差異

Which of the following function declarations will accept either cout or a file stream 
object as its argument? 

A. void output(fstream &outFile); 
B. void output(ofstream &outFile); 
C. void output(ostream &outFile); 
D. void output(iostream &outFile); 

答案是C.

我知道的區別:fstream的,ofstream的,ostream的,iostream的。

我不明白的是爲什麼沒有其他選項能夠接受cout或文件流對象作爲參數。

答案就像ostream對象包含可以作爲參數傳遞的數據(char等)一樣簡單嗎?

任何信息將不勝感激。

+2

也許[此C++ I/O參考](http://en.cppreference.com/w/cpp/io)及其繼承層次結構圖可以提供幫助嗎? –

+0

相關:[是否可以通過引用派生類來傳遞函數以基類作爲參數](https://stackoverflow.com/questions/9285627/is-it-possible-to-pass-derived-classes- by-reference-to-a-function-taking-base-cl) – Borgleader

+0

我會選擇'D',因爲可以輸入和輸出文件流。答案'C'只是輸出。 –

回答

2

答案是C.問題是關於繼承層次結構。 std::coutstd::ostream的一個實例。所有其他函數接受std :: ostream的子類,因此不能處理std::coutstd::fstream可以傳遞給他們所有人,但問題是關於兩者。

+1

http://www.cplusplus.com/reference/iolibrary/這可以幫助 –