2012-09-09 55 views
1

- EDIT - 非常抱歉,我迷惑人,我只是很快输入了这段代码而不是复制和粘贴,所以我实际上在代码中执行了#ifndef A_H #define A_H。我改变了以下代码,以显示
- 结束编辑 -结构无效的前向声明

我有两个类,其中每个包含一个指向另一个类的实例的指针,但这是为我创建问题。我的代码是类似于以下

// A.h 
#ifndef A_H 
#define A_H 

class B; // compiler error here 

class A 
{ 
    B* foo; 
    // other members and functions 
}; 

#endif 

// A.cpp 
#include "A.h" 
#include "B.h" 
/* 
declare functions and use methods in both A and B 
*/ 

// B.h 
#ifndef B_H 
#define B_H 

class A; 

class B 
{ 
    A** bar; 
// other stuff 
}; 

#endif 

//B.cpp 
#include "A.h" 
#include "B.h" 
/* 
declare functions and use methods in both A and B 
*/ 

有人告诉我,向前声明另一类诠释他的头文件则包括cpp文件将工作的其他文件,但在标线我得到一个错误,只是说“前向声明'结构b'”

任何人都可以告诉我我做错了什么?

+5

我想大胆猜测你的包括卫兵弄乱了班级名称。 – chris

+1

同意,'#define blah \ n class blah'将被'class [nothing here]'替换。 –

+1

Chrises,chrises无处不在。 – mfontanini

回答

3

包含一个头文件,让说b.h在a.h中。不要在a.h中转发declare B. b.h可以保持原样。

否则,你得到某物像

class B {}; 
.... 
class B; 

它始终是明智的,只能做这样的错误预处理。

+0

工作,谢谢 – Raphael