说我有以下两类:循环依赖
// a.h
#include "b.h"
和:
// b.h
include "a.h"
我知道有过一个问题在这里,但我怎么能解决这个问题,并使用a
对象和他们的方法在b
类中,反之亦然?
说我有以下两类:循环依赖
// a.h
#include "b.h"
和:
// b.h
include "a.h"
我知道有过一个问题在这里,但我怎么能解决这个问题,并使用a
对象和他们的方法在b
类中,反之亦然?
您可以使用所谓的“前向声明”。
对于函数,这会是这样void myFunction(int);
。对于一个变量,它可能看起来像extern int myVariable;
。对于一个班级,class MyClass;
。这些无形语句可以包含在实际的代码声明之前,并为编译器提供足够的信息来生成使用声明类型的代码。
为了避免出现问题具有圆形包括,使用“包括防护件” - 一个#ifdef
在这防止它的每个头文件的顶部被包括两次。
这个答案没有讨论这个东西的真正核心,那就是你限制你在'A'的标题中提到'B'来转发可声明的东西,但是在'A'的源文件中你可以自由地'#include'完整的定义,因为没有任何东西会包含'#include'源文件......你将不会有任何循环依赖关系。这个_only_会影响标题,这就是我们如何利用有效削弱类型使用的方法。 –
“其他”类只能具有引用或指向“第一个”类的指针。
文件啊:
#include "b.h"
struct a {
b m_b;
};
文件BH:
struct a;
struct b {
a* m_a;
};
void using_the_a_instance(b& theb);
文件b.cpp:
#include "b.h"
#include "a.h"
void using_the_a_instance(b& theb)
{
theb.m_a = new a();
}
要延长@Borealid的回答是:
为了避免通告中包含的问题,使用“包含警卫”
例如,
#ifndef MYFILE_H /* If this is not defined yet, it must be the first time
we include this file */
#define MYFILE_H // Mark this file as already included
// This only works if the symbol we are defining is unique.
// code goes here
#endif
StackOverflow上的幽灵说, “* Uhhhhhhnnnn ... Neeeeed moooore cooooode ...... *” –
我没有看到有什么课,所以我downvoting。 –