为什么要分别包含iostream和ostream?

问题描述:

我注意到很多人在C ++程序中分别包含iostream和ostream,就像这样:

I've noticed that many people include iostream and ostream in C++ programs separately, like so:

#include <iostream>
#include <ostream>
int main()
{
}

为什么会有人这样做?由于iostream继承自ostream,因此它应该包含所有内容,对吗?是否有一些晦涩的原因?简单的(std :: cout)代码怎么样?

Why would anyone do that? Since iostream inherits from ostream, it should include everything in it, right? Is there some obscure reason? What about simple (std::cout) code?

尽管stringstream继承自iostream,但未在<iostream>标头中声明. <iostream>标头包含iostream类型的定义以及著名的coutcerrcinclog类型,但不包含iostreams的其他类型(例如,文件流).对于这些,您确实需要明确地#include必需的头文件.

Although stringstream inherits from iostream, it is not declared in the <iostream> header. The <iostream> header contains the definition of the iostream type along with the famous cout, cerr, cin, and clog types, but not other types that are iostreams (for example, file streams). For these, you do need to explicitly #include the requisite header files.

编辑:针对您提出的修订问题,我提出了C ++规范,有趣的是,它不是<iostream>必须包含<ostream><istream>.实际上,仅包含<iosfwd>就可以摆脱困境.因此,有可能#include <iostream>实际上没有获得istreamostream的完整类定义.只有明确包括这些标头,才能保证这些类的 definitions (不仅仅是前向声明)是可见的.

EDIT: In response to your revised question, I pulled up the C++ spec and interestingly it does not say that <iostream> has to include either <ostream> or <istream>. In fact, it could get away with just including <iosfwd>. Consequently, it's possible to #include <iostream> without actually getting a full class definition for either istream or ostream. Only explicitly including those headers can guarantee that the definitions of those classes, not just the forward-declarations, are visible.