【问题标题】:Include file mess包括文件混乱
【发布时间】:2011-03-27 19:53:28
【问题描述】:

我有 2 个类 - 一个持有实体信息,另一个持有组件信息。 现在的问题是 Entity 类需要已经定义的 Component 类,以便在子向量中使用它,但同时 Component 需要 Entity 将其声明为它的父级(我将所有内容保持在两者之间)。这会产生奇怪的错误,即使 IntelliSense 说它都已经定义了。

我该如何克服这个困难?

【问题讨论】:

    标签: c++ class header header-files


    【解决方案1】:

    组件.h:

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

    实体.h:

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

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

    【讨论】:

    • 这很有效,谢谢!仍然以防万一我想看看有没有办法指出 使用方法。有什么建议吗?
    • 你可以使用.cpp文件中的方法,只是不能使用头文件。
    • 您当然可以在 Component 类中拥有调用实体方法的方法,只是不能将它们内联在 .h 文件中。您必须在类中为它们添加一个原型,然后在 component.cpp 文件中实现实现(包括 component.h 和 entity.h)。
    • 哦,那没关系!因为我只需要链接它们并在源文件中使用它们。谢谢!
    【解决方案2】:

    【讨论】:

      【解决方案3】:

      听起来你有这个:

      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.
      

      【讨论】:

      • 啊啊啊,你建议把它放到cpp文件中,并在标题中进行前向声明?谢谢!这很可能是我需要的!还有一件事困扰我,你包含了Entity.h,然后你包含了Component.h,那不是两次包含Entity吗?也许我可以使用定义来忽略在 compoenent.h 中包含实体?
      • 为了简洁起见,我省略了包含防护,因为它们是很常见的做法。为了完整起见,我会把它们放进去。
      【解决方案4】:

      一种选择是,如果您只在 vector 中使用指向 Component 的指针(即 vector&lt;Component*&gt;(或智能 ptr 变体)而不是 vector&lt;Component&gt;),您可以转发声明 Component 类和您的Entity 类声明不需要 Component 定义。

      【讨论】:

      • 我确实使用了vector,但这并没有解决它,因为我需要将实体中的this ptr分配给Copmonent对象中的pParent。
      • 所有的代码都写在头文件里了吗?您通常只想在头文件中进行声明。如果在 Entity 定义之前转发声明 (class Component;),则不必在头文件中包含 Component.h。当您实际初始化/使用您的 Component 对象时,您将在源文件中需要它,但包括来自 Entity.cppComponent.h 不会引入循环引用。
      • 当然不是,header 只用于定义。但是我已经想通了 - 我将它们包含在源文件中,并利用 #ifndef 包含保护(你知道我的意思)。
      猜你喜欢
      • 1970-01-01
      • 2014-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-13
      • 2017-01-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多