鉴于您描述问题的方式,我认为您的代码可能存在潜在的体系结构问题。
您的 ObjectFactory 应该处理 cEntities,而 cEntities 又应该不知道“上面的级别”。从您遇到的问题的描述来看,这意味着您不确定哪个班级负责什么工作。
您的 cEntity 应该公开一个接口(即类中所有标记为“公共”的东西),其他代码与之交互。您的 ObjectFactory (如果做这项工作,它的名字有点糟糕,但无论如何)应该反过来使用该接口。cEntitys 不应该关心谁在使用该界面:他们有一项工作要做,他们就去做。ObjectFactory 应该有一项工作需要它保留一个 cEntity 列表。当您在其他地方使用 std::string 时,您不会编辑它:为什么您的课程有什么不同?
话虽这么说,解决循环依赖关系有两个部分(除了“首先不要创建具有循环依赖关系的代码” - 请参阅此答案的第一部分。在我看来,这是避免此类问题的最佳方法)
1) 包括警卫。对每个标头 (.h) 文件执行以下操作:
#ifndef CENTITY_H
#define CENTITY_H
class cEntity:public cEntityProperty
{
Vector2 position;
Vector2 scale;
public:
cEntity(void);
cEntity(const cEntity&);
~cEntity(void);
public:
void init();
void render();
void update();
void release();
};
#endif
这是做什么的:
- 第一次包含您的文件时,未定义 CENTITY_H。因此,该
ifndef
宏为真,并移至下一行(定义 CENTITY_H),然后移至标题的其余部分。
- 第二次(以及所有未来的时间),定义了 CENTITY_H,所以
ifndef
宏直接跳到endif
,跳过你的标题。随后,您的头代码只会在您编译的程序中出现一次。如果您想了解更多详细信息,请尝试查找链接器流程。
2) 前向声明你的类。
如果 ClassA 需要 ClassB 类型的成员,而 ClassB 需要 ClassA 类型的成员,那么您就会遇到问题:两个类都不知道需要分配多少内存,因为它依赖于另一个包含自身的类。
解决方案是你有一个指向另一个类的指针。指针是编译器固定且已知的大小,所以我们没有问题。但是,我们确实需要告诉编译器不要太担心如果它遇到我们之前尚未定义的符号(类名),所以我们只需class Whatever;
在开始使用它之前添加。
在您的情况下,将 cEntity 实例更改为指针,并在开始时前向声明该类。您现在可以在 cEntity 中自由使用 ObjectFactory。
#include "cEntity.h"
#include <vector>
class cEntity; // Compiler knows that we'll totally define this later, if we haven't already
class ObjectFactory
{
static std::vector<cEntity*> *entityList; // vector of pointers
static int i, j;
public:
static void addEntity(cEntity* entity) {
entityList->push_back(entity);
}
// Equally valid would be:
// static void addEntity(cEntity entity) {
// entityList->push_back(&entity);}
// (in both cases, you're pushing an address onto the vector.)
// Function arguments don't matter when the class is trying to work out how big it is in memory
private:
ObjectFactory(void);
~ObjectFactory(void);
};
std::vector<cEntity*> *ObjectFactory::entityList = new std::vector<cEntity*>();