C++ circular header includes(C++ 循环头包括)
问题描述
我知道之前有人问过与此类似的问题,但经过研究后,我仍然对循环标题包含有疑问.
I know that similar questions to this have been asked before but after doing my research I still have questions about circular header includes.
//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
Now if I have two circular dependencies this is the way that I have seen people on stackoverflow get around the problem. My only problem with this is that in my main.cpp I must include fooa.h first and then 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 中包含头文件的顺序?"
Now my question is "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?"
推荐答案
有没有一种方法可以转发声明这些类,让我不必关心在 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?
由于您只处理简单的指针,因此您可以在这两种情况下使用前向声明:
since you are dealing with simple pointers only, you can use a forward declaration here in both cases:
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++ 循环头包括的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 循环头包括
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
