一个类需要另一个类,而另一个类需要第一个类。我怎么做?

时间:2012-08-03 09:44:41

标签: c++

这里我们有两个类,我们称之为TreeFruitTree在任何给定时间只能有一个Fruit个。 Fruit只能在一个Tree上。在Tree对象中,您可以通过函数Fruit获取getTreeFruit( )。从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包含了彼此的头文件,这会导致错误。我该如何解决错误?

非常感谢先进。 :)

4 个答案:

答案 0 :(得分:3)

您应该将引用存储在Fruit对象中的Tree中,而不是树本身。

参考文献是一个比指针更好的选择,因为它们表达了水果不能从一棵树神奇地跳到另一棵树的条件。只能在构造对象时设置引用,因此必须在构造函数中使用初始化列表。

然后,您可以使用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.

答案 1 :(得分: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.
}

答案 2 :(得分:1)

  

我意识到Tree和Fruit包含了彼此的头文件,这会导致错误。

这不是唯一的问题。基本上你希望两个对象以递归方式相互包含,这是不可能的。

你可能想要的是让水果指向它所属的树,并在Tree中向前声明Fruit.h,如下所示:

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.
}

答案 3 :(得分: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.
}