C++ 循环 header 包括

标签 c++ header header-files circular-dependency

<分区>

我知道之前有人问过与此类似的问题,但在进行研究后,我仍然对循环 header 包含有疑问。

//FooA.h
#ifndef H_FOOA
#define H_FOOA

#include "foob.h"

class FooA{
   public:
      FooB *fooB;
};


//FooB.h
#ifndef H_FOOB
#define H_FOOB

class FooA;
class FooB{
   public:
      FooA *fooA;
};

现在,如果我有两个循环依赖项,这就是我在 stackoverflow 上看到人们解决问题的方式。我唯一的问题是,在我的 main.cpp 中,我必须先包含 fooa.h,然后再包含 foob.h

//main.cpp the right way
#include "fooa.h"
#include "foob.h"

//main.cpp that will surely get a compile error
#include "foob.h"
#include "fooa.h"

现在我的问题是“有没有一种方法可以让我不关心在 main.cpp 中包含头文件的顺序来转发声明这些类?”

最佳答案

Is there a way to forward declare these classes in a way that will allow me to not care about the order in which I include the header files in my main.cpp?

因为你只处理简单的指针,你可以在这两种情况下使用前向声明:

FooA.h

#ifndef H_FOOA
#define H_FOOA

// #include "foob.h" << not needed!
class FooB;       // << substitute with a forward declaration of FooB

class FooA{
   public:
      FooB *fooB;
};
#endif

FooB.h

#ifndef H_FOOB
#define H_FOOB

class FooA;
class FooB{
   public:
      FooA *fooA;
};
#endif

关于C++ 循环 header 包括,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11971408/

相关文章:

c++ - 概念定义的放置如何改变程序行为

c++ - undefined reference to vtable 错误是由现代 g++ 编译器解决的吗?

c++ - 是否可以判断哪个数组元素比较结果为真?

c++ - 共享 header 导致多重定义符号错误

php - 将文件从一台服务器上传到另一台服务器(通过 HTTP POST)

c++ - C++创建头文件时,多个重载函数实例与参数列表匹配

c++ - 为什么我可以通过静态指针调用非静态函数?

android - recyclerview android中的多个 header

c++ - 带有 header 保护的目标文件

javascript - 编译嵌入式 SpiderMonkey 程序时出错