2012-08-03 215 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. 
相关问题