C++:如果我包含多个头文件,如果两者都有#include <string>,它会导致任何问题吗?

标签 c++ class

我正在尝试编写自己的小“游戏”,这就是我开始自己编程的原因。然而,使用多个头文件来声明由单独的 .cpps 使用的多个类给我带来了一个问题:如果我以后会造成任何伤害 #include <string>进入其中的每一个,并将这些标题中的多个包含到一个.cpp中? 一个例子:

//a.cpp
#include "x.h"
#include "y.h"
int main(){blablabla}

//x.h
#ifndef XCLASS_H #define XCLASS_H
#include <string>
class xclass{std::string xstring;};
#endif

//y.h
#ifndef YCLASS_H #define YCLASS_H
#include <string>
class yclass{std::string ystring;};
#endif

据我所知,两者都将包含到 a.cpp 中。当我尝试时,程序运行良好,没有任何错误。我正在使用 Visual Studio 2012。这会导致其他计算机出现问题吗?如果是,我该如何避免这些问题?

最佳答案

您可以在每个翻译单元中任意多次包含标准标题。

通常在第一个之后的后续包含将没有效果。

一个异常(exception)是 <assert.h> header ,它定义了 assert宏。此 header 可以定义 assert不同,取决于符号 NDEBUG , 每次都包括在内。由于这有点不寻常,标准明确指出了这一点。


标准语:

C++11 §17.6.22/2 [using.headers]:

A translation unit may include library headers in any order (Clause 2). Each may be included more than once, with no effect different from being included exactly once, except that the effect of including either <cassert> or <assert.h> depends each time on the lexically current definition of NDEBUG.

关于C++:如果我包含多个头文件,如果两者都有#include <string>,它会导致任何问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27749974/

相关文章:

c++ - 按钮 onClick 的工作原理

c++ - 为什么链接器在头文件中给出全局变量错误

html - <img> 变量计数的内联样式类

c++ - 如何使用 Eigen 库定义动态矩阵?

java - 您如何在对象类中实现枚举 - Java?

c++ - QML 双向 C++ 绑定(bind)不再接收更改

c++ - Bloomberg Api 连接问题 - <localhost :8194> Connection failed

c++ - 如何增加 boost::variant 可以处理的类型数量

c# - 自定义类框架/结构

java - Java 中的类转换异常