调用父对象上的成员函数
Calling member functions on a parent object?
我有两个类:World
和Entity
。
在World的内部,我有两个实体指针,我像这样做:
Entity* ent1;
Entity* ent2;
我想允许Entity对象调用World的公共成员函数。我认为我可以简单地将World的引用或指针传递给Entity。
但是当我从Entity.h
中包括World.h
时,我开始得到错误。这似乎有点错,因为他们包括彼此,但我没有其他的想法如何实现这个功能。
前向声明类Entity
在World.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
相关文章:
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 将公共但非静态的成员函数与ALGLIB集成
- 使用指向成员的指针将成员函数作为参数传递
- 将重载的成员函数传递给函数模板
- 我不小心调用了一个没有自己类对象的成员函数.但这是怎么回事呢
- 如何在C++中使用非静态成员函数作为回调函数
- C++错误C2600:无法定义编译器生成的特殊成员函数(必须首先在类中声明)
- 关联容器的下界复杂性:成员函数与非成员函数
- 在 C++ 中用派生类型重写成员函数
- 链表的泛型函数remove()与成员函数remove)
- 如何将lambda作为模板类的成员函数参数
- constexpr构造函数需要常量成员函数时出现问题
- 将自由函数绑定为类成员函数
- 区分非成员函数和头文件中的成员函数
- 如何从子成员函数修改父公共成员变量
- 保留对其他类的成员函数的引用
- 在运算符重载定义中使用成员函数(const错误)
- 内联如何影响模块接口中的成员函数
- 将成员函数指针作为参数传递给模板方法