2010-08-10 64 views
3

我有2个类 - 一个持有实体信息其他持有组件信息。 现在的问题是,实体类需要已经定义的组件类在儿童的矢量中使用它,但同时组件需要实体声明它为父(我保持所有链接之间)。即使IntelliSense表示它已全部定义,这也会引发奇怪的错误。包含文件混乱

我该如何克服这个困难?

回答

6

component.h:

class Entity; 
class Component { 
    ... 
    Entity *parent; 
}; 

entity.h:

#include "component.h" 
class Entity { 
    ... 
} 

唯一的缺点是这里在component.h不能使用实体法是内联方法。

+0

这工作谢谢! 仍然只是万一我想看看有没有办法指出_and_使用方法。任何建议? – Johnny 2010-08-10 13:20:25

+0

您可以使用.cpp文件中的方法,而不是标题。 – 2010-08-10 13:21:14

+0

您当然可以在Component类中调用Entity方法的方法,但您不能将它们内联在.h文件中。您必须在类中为它们添加原型,然后在component.cpp文件(包含component.h和entity.h)中实现该实现。 – 2010-08-10 13:21:57

3

这听起来像你有这样的:

Entity.h:

#include <vector> 

class Entity { 
public: 
    std::vector<Component> children; 
}; 

Component.h:

#include <Entity.h> 

class Component : public Entity { ... }; 

一种方法解决此问题是前向申报Component课程并使用vector指针Component S:

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 */ 

Component.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. 
+0

啊,你建议把它放到cpp文件中,然后在头文件中做一个前向声明?谢谢! 这很可能是我需要的! 仍然有一件事困扰我,你已经包含Entity.h,那么你包含Component.h,不会包括实体两次?也许我可以使用一个定义忽略compoenent.h中包含实体? – Johnny 2010-08-10 13:25:09

+0

为了简洁起见,我省略了包含警卫,因为它们很常见。我会把他们完整。 – 2010-08-10 13:36:29

1

一种选择是,如果你只是使用指针到Component在您的vector(即vector<Component*>(或智能ptr va riant)而不是vector<Component>),您可以转发声明Component类,并且您的Entity类声明不需要Component定义。

+0

我确实使用了矢量,但这并不能解决它,因为我需要从实体中将此ptr分配给Copmonent对象中的pParent。 – Johnny 2010-08-10 13:27:16

+0

你是否将所有代码写入头文件?你通常只想在头文件中做出声明。如果你在你的Entity定义之前转发declare('class Component;'),你将不必在头文件中包含'Component.h'。当你真正地初始化/使用你的Component对象时,你将需要它在源文件中,但是包括来自Entity.cpp的Component.h不会引入循环引用。 – bshields 2010-08-10 13:31:46

+0

当然不是,标题仅用于定义。 但是我已经想通了 - 我将它们包含在源文件中,并利用#ifndef包含保护(您知道我的意思)。 – Johnny 2010-08-10 13:34:03