2012-08-03 213 views
0

這裏我們有兩個類,我們稱之爲TreeFruit。 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. 
} 

我意識到TreeFruit包括對方的頭文件,這會導致錯誤。我該如何着手解決這個錯誤?

非常感謝先進的。之類的:)

回答

1

我意識到,樹和水果包括對方的頭文件這會導致錯誤。

這不是唯一的問題。基本上你想要兩個對象遞歸地包含對方,這是不可能的。

你可能想要的是做水果有一個指向它所屬的樹,並在Fruit.h前瞻性聲明Tree像這樣:

tree.h中:

#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.h

class Tree; 

class Fruit 
{ 
    private: 
     Tree* m_Owner; // The Tree object that "owns" the fruit. 

    public: 
     Fruit(Tree* fruit_owner); 
     Tree* getFruitOwner(); // Returns m_Owner. 
} 
+0

我做到了。有效。現在,我有另一種名爲'drawFruit()'的方法,該方法採用'Fruit'所有者的'x'位置,並在某些數學運算後使用該值來定位水果。但是,我收到錯誤說'會員訪問不完整類型'樹'。那是什麼意思?我必須在我的'Fruit.cpp'中包含'Tree.h'嗎?順便說一句,樹的'x'值是公開的。 – alxcyl 2012-08-03 10:11:07

+0

@LanceGray準確。 – 2012-08-03 10:12:31

+0

我收到一個錯誤消息,說:「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

1

使用前聲明,使樹指針

class Tree; 
class Fruit { 
    private: 
     Tree *m_pOwner; // The Tree object that "owns" the fruit. 

    public: 
     Fruit (Tree *fruit_owner); 
     Tree* getFruitOwner(); // Returns m_Owner. 
} 
0

你應該使用forward declaration

class Tree; 

class Fruit { 
    private: 
     Tree *m_Owner; // The Tree object that "owns" the fruit. 

    public: 
     Fruit (Tree *fruit_owner); 
     Tree *getFruitOwner(); // Returns m_Owner. 
} 
3

你應該存儲在水果對象引用的樹木,而不是我的樹自行宣佈。

引用是一個比指針更好的選擇,因爲它們表達了水果不能神奇地從一棵樹跳到另一棵樹的條件。引用只能在構造對象時設置,因此必須在構造函數中使用初始化程序列表。

然後,您可以使用Tree的前向聲明。

class Tree; 

    class Fruit { 
    private: 
     Tree &owner; // The Tree object that "owns" the fruit. 

    public: 
     Fruit (Tree &fruit_owner) : owner(fruit_owner) 
     { ... }; 

     Tree &getFruitOwner(); // Returns owner. 
相關問題