为什么省略“#include <string>"?只是有时会

Why does omission of quot;#include lt;stringgt;quot; only sometimes cause compilation failures?(为什么省略“#include string?只是有时会导致编译失败?)
本文介绍了为什么省略“#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.

这篇关于为什么省略“#include <string>"?只是有时会导致编译失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)