【发布时间】:2011-03-27 19:53:28
【问题描述】:
我有 2 个类 - 一个持有实体信息,另一个持有组件信息。 现在的问题是 Entity 类需要已经定义的 Component 类,以便在子向量中使用它,但同时 Component 需要 Entity 将其声明为它的父级(我将所有内容保持在两者之间)。这会产生奇怪的错误,即使 IntelliSense 说它都已经定义了。
我该如何克服这个困难?
【问题讨论】:
标签: c++ class header header-files
我有 2 个类 - 一个持有实体信息,另一个持有组件信息。 现在的问题是 Entity 类需要已经定义的 Component 类,以便在子向量中使用它,但同时 Component 需要 Entity 将其声明为它的父级(我将所有内容保持在两者之间)。这会产生奇怪的错误,即使 IntelliSense 说它都已经定义了。
我该如何克服这个困难?
【问题讨论】:
标签: c++ class header header-files
组件.h:
class Entity;
class Component {
...
Entity *parent;
};
实体.h:
#include "component.h"
class Entity {
...
}
这里唯一的缺点是component.h中的内联方法不能使用Entity方法。
【讨论】:
【讨论】:
听起来你有这个:
Entity.h:
#include <vector>
class Entity {
public:
std::vector<Component> children;
};
组件.h:
#include <Entity.h>
class Component : public Entity { ... };
解决此问题的一种方法是前向声明Component 类并使用指向Components 的vector 指针:
Entity.h:
#ifndef ENTITY_H
#define ENTITY_H
#include <vector>
class Component; // Forward declaration.
class Entity {
public:
std::vector<Component*> children;
};
#endif /* ndef ENTITY_H */
组件.h:
#ifndef COMPONENT_H
#define COMPONENT_H
#include <Entity.h> // To allow inheritance.
class Component : public Entity { ... };
#endif /* ndef COMPONENT_H */
Entity.cpp:
#include <Entity.h>
#include <Component.h> // To access Component members.
【讨论】:
一种选择是,如果您只在 vector 中使用指向 Component 的指针(即 vector<Component*>(或智能 ptr 变体)而不是 vector<Component>),您可以转发声明 Component 类和您的Entity 类声明不需要 Component 定义。
【讨论】:
Entity 定义之前转发声明 (class Component;),则不必在头文件中包含 Component.h。当您实际初始化/使用您的 Component 对象时,您将在源文件中需要它,但包括来自 Entity.cpp 的 Component.h 不会引入循环引用。