fstream、ofstream、ostream、iostream的区别

Hum*_*543 5 c++ fstream iostream ofstream ostream

我正在参加 C++ 入门级课程的测验,我正在尝试理解一个问题。在互联网上搜索并没有得到答案后,所以我在这里。

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);
Run Code Online (Sandbox Code Playgroud)

答案是 C。

我知道以下区别:fstream、ofstream、ostream、iostream。

我不明白的是为什么其他选项都不能接受 cout 或文件流对象作为参数。

答案是否像 ostream 对象包含能够作为参数传递的数据(字符等)一样简单?

任何信息将不胜感激。

小智 6

答案是C。问题是关于继承层次结构的。std::cout是 的一个实例std::ostream。所有其他函数接受 std::ostream 的子类,因此无法处理std::cout. std::fstream可以传递给他们所有人,但问题是关于两者的。