2011-03-11 125 views
0

在C++中,我有A.h和B.h. 我需要在B.h中包含A.h,那么我需要在A.cpp中使用B中的一个对象。所以我把A.h包括在A.h中,所以它拒绝了。 我试着在.h文件中使用这些线路C++包含 - 交叉引用文件

#ifndef A_H 
#define A_H 
...my code 
#endif 

我有同样的拒绝。 所以我试着在A.h文件中把

class B; 

作为定义的类。 所以它把它作为另一个班级不是我想要的B班。 我要做什么?

+0

另请参阅:http://stackoverflow.com/questions/4889462/cyclic-dependency-headers-and-templates – phooji 2011-03-11 22:54:38

+0

对不起,你的描述有点混乱G。发布所有文件的示例代码将有所帮助。 – Mahesh 2011-03-11 22:58:37

+0

请在您的问题中使用标点符号和适当的大写字母。如果你不能花时间来清楚地交流,你为什么期望这里的人花时间来清楚地回答? – 2011-03-12 00:11:15

回答

1

您不能在B.h中包含A.h,在A.h中也包含B.h--它是循环依赖。

如果A中的结构或函数需要引用指向B中结构的指针(反之亦然),那么您可以声明结构而不定义它们。

在A.H:

#ifndef __A_H__ 
#define __A_H__ 

struct DefinedInB; 

struct DefinedInA 
{ 
    DefinedInB* aB; 
}; 

void func1(DefinedInA* a, DefinedInB* b); 

#endif __A_H__ 

在B.h:

#ifndef __B_H__ 
#define __B_H__ 

struct DefinedInA; 

struct DefinedInB 
{ 
    DefinedInA* anA; 
}; 

void func2(DefinedInA* a, DefinedInB* b); 

#endif __B_H__ 

你只能用指针做到这一点,又避免了循环依赖。

0

在一般情况下,最好是避免循环引用,但是如果你需要他们在你的设计,你的依赖性如下:

a.h <-- b.h <-- a.cpp (where x <-- y represents "y" depends on "x") 

只需键入在:

// A.h 
#ifndef A_HEADER 
#define A_HEADER 
... 
#endif 

// B.h 
#ifndef B_HEADER 
#define B_HEADER 
#include "A.h" 
... 
#endif 

// A.cpp 
#include "A.h" 
#include "B.h" 
// use contents from both A.h and B.h 
+0

但在A.h中的问题我有一个参数从B – soufi 2011-03-11 23:24:52