2012-09-09 53 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