0

ここに2つのクラスがあります。それTreeをとと呼びましょうFruit。ATreeは、常に1つだけまたはまったく持つことができませんFruit。AFruitは1つだけにできますTree。オブジェクトから、関数でTree取得できます。オブジェクトから、オブジェクトを返す関数によってその「所有者」を取得できます。FruitgetTreeFruit( )FruitgetFruitOwner( )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エラーを修正するにはどうすればよいですか?

よろしくお願いします。:)

4

4 に答える 4

3

ツリー自体ではなく、Fruitオブジェクトにツリーへの参照を保存する必要があります。

参照は、果物が1つのツリーから別のツリーに魔法のようにホップできないという条件を表すため、ここでのポインターよりも適切な選択です。参照はオブジェクトの構築時にのみ設定できるため、コンストラクターで初期化子リストを使用する必要があります。

次に、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.
于 2012-08-03T09:50:47.167 に答える
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.
}
于 2012-08-03T09:47:54.050 に答える
1

TreeとFruitにはお互いのヘッダーファイルが含まれていることに気づきました。これによりエラーが発生します。

これだけが問題ではありません。基本的に、2つのオブジェクトを再帰的に相互に含める必要がありますが、これは不可能です。

おそらく必要なのは、フルーツにそれが属するツリーへのポインターを持たせ、次のように前方宣言することですTreeFruit.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.
}
于 2012-08-03T09:49:47.700 に答える
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.
}
于 2012-08-03T09:48:13.197 に答える