2013-06-21 20 views
4

我需要的是創建兩個類,它們相互使用。在C++中共存的類

例如:

Class A包含Class B類型的對象,並Class B包含類型Class A

但是,當我編譯的對象,這是發生了什麼:「錯誤:ISO C++禁止地圖的」聲明'沒有類型'

我修改了我的類,保持Header(.h)文件分開,但它沒有解決。

也許,這是一個基本的問題,但我不知道在谷歌搜索的關鍵詞...

代碼:

Cell.h:

Class Cell 
{ 
public: 
    Map *map; 
} 

Map.h :

Class Map 
{ 
public: 
    Cell *cell; 
} 
+0

你是什麼意思的「含」?顯然,'A'和'B'不能有對方的實例作爲成員... –

+0

是的,他們可以@OliCharlesworth ... –

+1

@IvanSeidel:他們肯定不能,因爲那樣會導致無限遞歸。然而,他們可以指出*或*參照*彼此的實例(例如通過「地圖」)的成員。 –

回答

1

如果class A包含class Bclass B還包含一個class A則沒有,你不能這樣做。

class B; // forward declaration of name only. Compiler does not know how much 
     // space a B needs yet. 

class A { 
    private: 
     B b; // fail because we don't know what a B is yet. 
}; 

class B { 
    private: 
     A a; 
}; 

即使這可行,也無法構建任一個的實例。

B b; // allocates space for a B 
    // which needs to allocate space for its A 
    // which needs to allocate space for its B 
    // which needs to allocate space for its A 
    // on and on... 

然而,可以包含彼此的指針(或引用)。

class B; // forward declaration tells the compiler to expect a B type. 

class A { 
    private: 
     B* b; // only allocates space for a pointer which size is always 
       // known regardless of type. 

}; 

class B { 
    private: 
     A* a; 
}; 
+0

我試圖添加只是指針。它工作,謝謝 –

2

你的情況的問題是,你有遞歸包括。 Cell.h包括Map.h其中包括Cell.h。相反,包括像這樣的只是向前聲明的類:

Cell.h

class Map; 

class Cell 
{ 
    // ... 
} 

Map.h

class Cell; 

class Map 
{ 
    // ... 
} 
3

你想向前聲明和指針。

//a.h 
class B; //forward declare than a class B, exist somewhere, although it is not completely defined. 

class A{ 
map<string,B*> mapOfB; 
}; 

//b.h 
class A; //forward declare than a class A, exist somewhere, although it is not completely defined. 
class B{ 
map<string,A*> mapOfA; 
} 

,並在您.CXX你實際上包括必要的頭

//a.cxx 
#include "b.h" 
A::A(){ /* do stuff with mapOfB */ } 

//b.cxx 
#include "a.h" 
B::B(){ /* do stuff with mapOfA */ } 
+0

共享指針將是一個更好的選擇,但要小心循環引用。 – Joel

+0

是的,但只是保持輕/如示例 – dchhetri

+0

通常,共享指針比原始指針更簡單。 – aschepler