如何在C ++中更清楚地包含头文件

在C ++中,我有一些头文件,例如: Base.h ,以及一些使用Base.h类:

 //OtherBase1.h #include "Base.h" class OtherBase1{ // something goes here }; //OtherBase2.h #include "Base.h" class OtherBase2{ // something goes here }; 

main.cpp ,由于重复的标题,我只能使用这两个OtherBase类中的一个。 如果我想使用这两个类,在OtherBase2.h我必须#include "OtherBase1.h"而不是#include "Base.h" 。 有时,我只想使用OtherBase2.h而不是OtherBase1.h ,所以我认为在OtherBase2.h包含OtherBase1.h真的很奇怪。 我该怎么做才能避免这种情况以及包含头文件的最佳做法是什么?

您应该在Base.h使用包含 Base.h

一个例子:

 // Base.h #ifndef BASE_H #define BASE_H // Base.h contents... #endif // BASE_H 

这将防止多次包含Base.h ,并且您可以使用两个OtherBase标头。 OtherBase标头也可以使用包含OtherBase

基于某个头中定义的API的可用性,常量本身对于代码的条件编译也是有用的。

替代方案: #pragma once

请注意, #pragma once可用于完成同样的事情,没有与用户创建的#define常量相关的一些问题,例如名称冲突,偶尔键入#ifdef而不是#ifndef的小麻烦,或忽略关闭条件。

#pragma once通常可用但包含警卫始终可用。 事实上,您经常会看到表单的代码:

 // Base.h #pragma once #ifndef BASE_H #define BASE_H // Base.h contents... #endif // BASE_H 

您必须使用标头防护来避免重复。

http://en.wikipedia.org/wiki/Include_guard

例如,在您的Base.h添加以下内容:

 #ifndef BASE_H_ #define BASE_H_ // stuff in Base.h #endif 

对于听到的警卫格式,请参阅此SO问题

#include标头保护格式?

为避免出现与多次导入相同头文件相关的问题,可以使用预处理器来防范。 通常的方法是将这些位添加到Base.h

 #ifndef BASE_H_CONSTANT #define BASE_H_CONSTANT // Stick the actual contents of Base.h here #endif