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

编程入门 行业动态 更新时间:2024-10-25 06:24:13
本文介绍了为什么要分别包含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类型的定义以及著名的cout,cerr,cin和clog类型,但不包含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>实际上没有获得istream或ostream的完整类定义.只有明确包括这些标头,才能保证这些类的 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.

更多推荐

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

本文发布于:2023-11-24 03:38:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1623836.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:iostream   ostream

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!