为什么需要包含C++头文件的保护?

Pra*_*tik 5 c++ header-files

我粗略地了解它的作用.我不明白为什么它不是默认值?有些头文件需要多次包含的用例有哪些?

Jer*_*ner 8

它不是默认的原因主要是历史 - 当C语言被正式化时,#include被指定它必须完全像用户在#include-line 的位置复制并粘贴指定文件的内容一样; 和C++希望(并希望)保持与C尽可能兼容,因此C++从C继承了这种行为.

对于多次包含相同头文件的用例可能是有用的; 我发现它有用的一个实例是在C中模拟模板化容器类(因为C不直接支持模板).我有一个容器实现头文件看起来像这样(但更详细;我在这里显示简化版本的可读性):

// MyContainerImplemention.h
// be sure to #define MYTYPE and MYARRAYSIZE
// before #include-ing this file!

struct ArrayOf##MYTYPE
{
   MYTYPE arrayOfItems[MYARRAYSIZE];
};

inline void Set##MYTYPE##Item(struct ArrayOf##MyType * container, int which, MYTYPE item) 
{
   container[which] = item;
}

[... and so on for various other MYTYPE-specific methods ...]
Run Code Online (Sandbox Code Playgroud)

...然后我的.c文件可以做类似的事情:

#define MYTYPE int
#define MYARRAYSIZE 10
#include "MyContainerImplementation.h"
#undef MYARRAYSIZE
#undef MYTYPE

#define MYTYPE short
#define MYARRAYSIZE 15
#include "MyContainerImplementation.h"
#undef MYARRAYSIZE
#undef MYTYPE

struct ArrayOfint myInts;
struct ArrayOfshort myShorts;

SetintItem(&myInts, 5, 12);
SetshortItem(&myShorts, 3, 2);
[...]
Run Code Online (Sandbox Code Playgroud)

...最终得到容器"class"及其为每种数据类型实现的相关方法,而不必每次都手动编写容器"class"的新实现.

是的,它非常难看 - 但不像手动写出数千行冗余容器代码一样难看.(真正的container-implementation-header-file实现了一个哈希表,并且有几百行)