c++ 中的循环依赖关系
假设我有这两个类:
// a.h
#include "b.h"
并且:
// b.h
include "a.h"
我知道这里有问题,但是我如何修复它并在 b
类和副类中使用 a
对象及其方法反之亦然?
Say I have these two classes:
// a.h
#include "b.h"
and:
// b.h
include "a.h"
I understand there is a problem over here, but how can I fix it and use a
objects and their methods in b
class and vice versa?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用前向声明,如下所示:
有关详细信息,请参阅这个 SO问题。
至于预处理器
#include
,可能有更好的方法来组织代码。但如果没有完整的故事,就很难说。You can use forward declarations, like this:
For more information, see this SO question.
As for the preprocessor
#include
s, there's likely a better way to organize your code. Without the full story, though, it's hard to say.扩展@Borealid 的答案:
例如。
To extend on @Borealid 's answer:
eg.
您可以使用所谓的“前向声明”。
对于函数,这类似于
void myFunction(int);
。对于变量,它可能类似于extern int myVariable;
。对于类,class MyClass;
。这些无实体语句可以包含在实际的代码承载声明之前,并为编译器提供足够的信息来生成使用声明类型的代码。为了避免循环包含的问题,请使用“包含防护” - 每个头文件顶部的
#ifdef
,以防止它被包含两次。You can use what is called a "forward declaration".
For a function, this would be something like
void myFunction(int);
. For a variable, it might look likeextern int myVariable;
. For a class,class MyClass;
. These bodiless statements can be included before the actual code-bearing declarations, and provide the compiler with enough information to produce code making use of the declared types.To avoid problems with circular includes, using an "include guard" - an
#ifdef
at the top of each header file which prevents it being included twice.“其他”类只能具有指向“第一个”类的引用或指针。
在文件 ah 中:
在文件 bh 中:
在文件 b.cpp 中:
The "other" class can only have a reference or pointer to the "first" class.
in file a.h:
in file b.h:
in file b.cpp: