调用父对象上的成员函数

Calling member functions on a parent object?

本文关键字:成员 函数 对象 调用      更新时间:2023-10-16

我有两个类:WorldEntity

在World的内部,我有两个实体指针,我像这样做:

Entity* ent1;
Entity* ent2;

我想允许Entity对象调用World的公共成员函数。我认为我可以简单地将World的引用或指针传递给Entity。

但是当我从Entity.h中包括World.h时,我开始得到错误。这似乎有点错,因为他们包括彼此,但我没有其他的想法如何实现这个功能。

在其他编程语言中,我看到过父关键字,在c++中有类似的东西吗?

前向声明类EntityWorld.h.

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();
}

你可以做的是使父类中的方法为virtual,并在实体类中重写它。

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

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

从你的描述我的猜测是你有一些循环依赖的问题。你曾经试过使用#pragma吗?这里有一个参考链接。如果你不喜欢,你也可以尝试在每个标题中添加一些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