Why would I include iostream and ostream separately? [duplicate]

穿精又带淫゛_ 提交于 2019-12-19 06:46:01

问题


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

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

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?


回答1:


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.

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.




回答2:


iostream explicitly includes istream and ostream (C++0x requires this, and the gnu libstdc++ version does this), so ostream is technically unnecessary

for future reference:

fstream contains the declaration for fstream (file streams),

sstream contains the declaration for stringstream (string streams)

iostream declares the standard i/o facilities (e.g. cin, cout, ...)

iosfwd is the standard header that forward-declares the major types.



来源:https://stackoverflow.com/questions/4930176/why-would-i-include-iostream-and-ostream-separately

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!