我正在尝试编写自己的小“游戏”,这就是我开始自己编程的原因。然而,使用多个头文件来声明由单独的 .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 ofNDEBUG
.
关于C++:如果我包含多个头文件,如果两者都有#include <string>,它会导致任何问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27749974/