gpt4 book ai didi

c++ - 在父对象上调用成员函数?

转载 作者:行者123 更新时间:2023-11-28 07:39:15 26 4
gpt4 key购买 nike

我有两个类:WorldEntity

在世界内部,我有两个实体指针,它们是这样制作的:

Entity* ent1;
Entity* ent2;

我想让 Entity 对象调用 World 的公共(public)成员函数。我想我可以简单地将 World 的引用或指针传递给实体。

但是当我从 Entity.h 中包含 World.h 时,我开始出现错误。这似乎有点不对劲,因为它们相互包含,但我不知道如何实现此功能。

在其他编程语言中我见过parent 关键字,在 C++ 中有类似的东西吗?

最佳答案

World.h 中转发声明类 Entity

世界.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;
};

实体.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;
};

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

关于c++ - 在父对象上调用成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16157976/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com