开发者

Include file mess

I'm having 2 classes - one holding Entity information other holding Component information. Now the problem is that the Entity class needs Component class already defined for using it in vector of children, but at the same time Component needs Entity to declare it as it's parent (I'm keeping everything linked in between). This puts开发者_如何学运维 out strange errors, even though IntelliSense says it's all already defined.

How can I overcome this difficulty?


component.h:

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

entity.h:

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

The only drawback here is that inline methods in component.h cannot use Entity methods.


It sounds like you have this:

Entity.h:

#include <vector>

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

Component.h:

#include <Entity.h>

class Component : public Entity { ... };

One way around the issue is to forward-declare the Component class and use a vector of pointers to Components:

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.


Use forward declaration


One option is if you just use pointers to Component in your vector (ie vector<Component*> (or a smart ptr variant) instead of vector<Component>), you could forward declare the Component class and your Entity class declaration wouldn't need the Component definition.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜