這裏我們有兩個類,我們稱之爲Tree
和Fruit
。 A Tree
在任何給定時間只能有一個或沒有Fruit
。 A Fruit
只能在一個Tree
上。從Tree
對象,您可以通過功能getTreeFruit()
獲得其Fruit
。從Fruit
對象中,可以通過函數getFruitOwner()
獲取其「所有者」,該函數返回Tree
對象。一個班級需要另一個班級,其他班級需要第一個班級。我怎麼做?
現在在Tree
頭,我們有這樣的:
#include "Fruit.h"
class Tree {
private:
Fruit m_Fruit; // The fruit in the tree.
public:
Tree (Fruit tree_fruit);
Fruit getTreeFruit(); // Returns m_Fruit.
}
而且在Fruit
頭:
#include "Tree.h"
class Fruit {
private:
Tree m_Owner; // The Tree object that "owns" the fruit.
public:
Fruit (Tree fruit_owner);
Tree getFruitOwner(); // Returns m_Owner.
}
我意識到Tree
和Fruit
包括對方的頭文件,這會導致錯誤。我該如何着手解決這個錯誤?
非常感謝先進的。之類的:)
我做到了。有效。現在,我有另一種名爲'drawFruit()'的方法,該方法採用'Fruit'所有者的'x'位置,並在某些數學運算後使用該值來定位水果。但是,我收到錯誤說'會員訪問不完整類型'樹'。那是什麼意思?我必須在我的'Fruit.cpp'中包含'Tree.h'嗎?順便說一句,樹的'x'值是公開的。 – alxcyl 2012-08-03 10:11:07
@LanceGray準確。 – 2012-08-03 10:12:31
我收到一個錯誤消息,說:「Tree :: Tree(std :: string const&)Tree.o中的樹形結構i386的未定義符號: 」Fruit :: Fruit()「,引用來自: Tree :: Tree(int ,int,std :: string const&)在Tree.o ld:符號(s)not found for architecture i386' – alxcyl 2012-08-03 10:18:10