我应该包含一个已经通过其他头文件包含的头文件吗? [英] should I include a header that is already included via other headers?

查看:132
本文介绍了我应该包含一个已经通过其他头文件包含的头文件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只注意到我的程序使用字符串类进行编译,而不包括< string> 标头。事实证明,< iostream> 包括< ios_base> ,它又包括< ; string>



这是不好的做法,我应该明确地包含< string> ?即使它只是一个清晰的情况?



假设这适用于< string> 标题?也许这是特定于实现的,或者标准状态是通过< ios_base> 来包含< string>和< iostream> ?确保任何受到尊重和广泛使用的实现将始终包含< string> ,以提供对< iostream> 存在。

解决方案



没有指定其他标准库头包含哪些标准库头,因此编译器之间的这些细节会有所不同。



您可以依赖另一个头文件包含的头文件的情况是,一个头文件中的类派生自另一个头文件中的类。例如,< iostream> 必须包含< ios_base> ,因为在 < iostream> 是从< ios_base> 中定义的类派生的。


I had only just noticed my programs using the string class were compiling without including the <string> header. It turns out that <iostream> includes <ios_base> which in turn includes <string>.

Is this bad practice and should I explicitly include <string>? Even if it's just a case of clarity?

Is it safe to assume this applies to more than just the <string> header? Perhaps this is implementation specific and or does the standard state the <string> header be included via <ios_base> and <iostream>? Ensuring that any respected and widely used implementation will always include <string> providing the the call to <iostream> exists.

解决方案

You should explicitly include whatever standard library headers you need.

It is not specified which standard library headers are included by other standard library headers, so such details will differ between compilers.

One case where you can rely on a header being included by another header is if a class in one header derives from a class in another. For example, <iostream> has to include <ios_base> because classes defined in <iostream> are derived from classes defined in <ios_base>.

这篇关于我应该包含一个已经通过其他头文件包含的头文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆