0

と の 2 つのクラスWorldがありEntityます。

ワールド内には、次のように作成した 2 つのエンティティ ポインターがあります。

Entity* ent1;
Entity* ent2;

Entity オブジェクトが World の public メンバー関数を呼び出せるようにしたかったのです。World の参照またはポインタをエンティティに渡すだけでよいと考えました。

しかし、World.hfromを含めるとEntity.h、エラーが発生し始めます。それらが互いに含まれているため、少し間違っているように見えますが、この機能を実現する方法について他に考えがありません。

キーワードを見た他のプログラミング言語では、C++ にそのようなものはありますか?

4

3 に答える 3

1

World.hでクラスEntityを前方宣言します。

World.h:

class Entity; // #include "Entity.h" is not needed, because
              // only a pointer to Entity is used at the moment.

class World {
  public:
    void foo() {}

    void letEntityDoFooToMe(); // Implementation must be defined later, because it
                               // will use the whole Entity class, not just a
                               // pointer to it.
  private:
    Entity* e;
};

Entity.h:

#include "World.h" // Needed because Entity::doFooToWorld calls a method of World.

class Entity {
  public:
    Entity(World& world) : w(world) {}

    void doFooToWorld() {
      w.foo();
    }

  private:
    World& w;  
};

World.cpp:

#include "World.h"  // Needed because we define a method of World.
#include "Entity.h" // Needed because the method calls a method of Entity.

void World::letEntityDoFooToMe() {
  e->doFooToWorld();
}
于 2013-04-22T22:51:38.860 に答える
0

できることは、親クラスのメソッドを仮想にして、エンティティ クラスでオーバーライドすることです。

class World
{
public:
    virtual void Func();
}


class Entity: public World
{
public:
    void Func();
}
于 2013-04-22T22:48:30.407 に答える
0

あなたの説明から、循環依存の問題が発生していると思います。#pragma once を使用しようとしましたか。ここに参照リンクがあります。それが気に入らない場合は、それぞれのヘッダーに ifndef を追加してみてください。

// World.h
#ifndef WORLD_H
#define WORLD_H

// ... World declaration code goes here.

#endif

// Entity.h
#ifndef ENTITY_H
#define ENTITY_H

// ... Entity declaration code goes here.

#endif
于 2013-04-22T22:49:06.043 に答える