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

Kin*_*uoc 2 c c++ header-files

在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
};
Run Code Online (Sandbox Code Playgroud)

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

pb2*_*b2q 8

您应该使用包括守卫Base.h.

一个例子:

// Base.h
#ifndef BASE_H
#define BASE_H

// Base.h contents...

#endif // BASE_H
Run Code Online (Sandbox Code Playgroud)

这将防止多次包含Base.h,您可以使用两个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
Run Code Online (Sandbox Code Playgroud)