首页 > 解决方案 > 引用成员类中的父类 - 包含循环

问题描述

我正在用 C++ 和 SDL 构建游戏引擎,我正在实现一个实体组件系统。我有一个类实体,它有一个组件的 std::map,我有一个类组件,以及一个从它派生的子类,称为外观。在 Component 父类中,我有一个指向父类的指针,用于获取组件之间的信息。我不能在外观.h 中包含 entity.h,因为 entity.h 包含外观.h,这将创建一个不合法的包含循环......目前我正在做class Entity;的组件开始工作,直到我使用实体的实际成员,这是必不可少的。

不是真实的但类似的代码:

component.h,没有错误

class Entity;

class Component
{
    Entity* parent;

    Component(Entity* parent) : parent(parent) {}
};

外观.h,由于类型不完整而有错误

#include "component.h"

class Entity;

class Appearance : public Component
{
    Appearance(Entity* parent) : Component(parent) {}
    render() { renderAt(parent->transform.position); /* Uses members of parent */ }
};

entity.h,没有错误

#include "component.h"
#include "appearance.h"
#include <map>

class Entity
{
private:
    std::map<int, Component> components;
public:
    Transform transform;

    Entity() {}

    void foo() { Appearance a(this); /* Uses appearance.h */ }
};

我该怎么办?

标签: c++classooppointersincomplete-type

解决方案


推荐阅读