为什么省略“#include <string>"?只是有时会导致编译失败?
我是 C++ 的初学者.当我编写代码时,有时我会写 #include
并且代码有效,有时我不写 #include
并且代码没有不行.但有时它可以在没有 #include
的情况下工作.
I am a beginner with C++. When I write the code sometimes I write #include <string>
and the code works, other times I don't write #include <string>
and the code doesn't work. But sometimes it works without #include <string>
.
那么我是否必须编写 #include <string>
才能使代码有效?
So do I have to write #include <string>
so that the code works?
推荐答案
如果您使用在标准标头 string
内声明的成员,那么是的,您必须直接或间接包含该标头(通过其他标题).
If you use members that are declared inside the standard header string
then yes, you have to include that header either directly or indirectly (via other headers).
某些 编译器在 some 平台上可能会在每月的 某些 时间编译,即使您没有包含头文件.这种行为令人遗憾、不可靠,并不意味着您不应包含标题.
Some compilers on some platforms may on some time of the month compile even though you failed to include the header. This behaviour is unfortunate, unreliable and does not mean that you shouldn’t include the header.
原因很简单,您包含了其他标准标题,也恰好包含string
.但正如我所说,这通常不能依赖,它也可能会突然发生变化(例如,当安装了新版本的编译器时).
The reason is simply that you have included other standard headers which also happen to include string
. But as I said, this can in general not be relied on and it may also change very suddenly (when a new version of the compiler is installed, for instance).
始终包含所有必要的标题.不幸的是,似乎没有可靠的在线文档来说明需要包含哪些标题.查阅一本书或官方的 C++ 标准.
Always include all necessary headers. Unfortunately, there does not appear to be a reliable online documentation on which headers need to be included. Consult a book, or the official C++ standard.
例如,以下代码使用我的编译器 (gcc
4.6) 进行编译:
For instance, the following code compiles with my compiler (gcc
4.6):
#include <iostream>
int main() {
std::string str;
}
但是如果我删除第一行,即使 iostream
标头实际上应该是无关的,它也不再编译.
But if I remove the first line, it no longer compiles even though the iostream
header should actually be unrelated.
相关文章