【问题标题】:including multiple related classes without looping includes包括多个相关类而不循环包括
【发布时间】:2022-06-17 02:58:30
【问题描述】:

我在将多个标题与相互依赖的类链接时遇到问题:

  • Entity.hpp 我有 Entity

  • Manager.hpp 我有 Manager

  • Scene.hpp 我有 Scene

Scene 存储 Manager 存储多个 Entity 实例,但是:

Entity 类有一个指向 Scene 的指针(使用 Manager

Entity.hpp

#include "Scene.hpp"

class Entity
{
public:

    Entity(Scene* scene_ref);
    Entity(const Entity& other);
    ~Entity();

    entityID ID() const; // example of normal function (defined in .cpp file)

    template <typename ComponentType, typename... Args>
    void addComponent(Args&&... args); // example of template function


private:

    Scene* m_scene_ref;
    entityID m_ID;
};


template <typename ComponentType, typename ...Args>
inline void Entity::addComponent(Args&& ...args) // definition of template function
{
    m_scene_ref->component_registry.add<ComponentType>(m_ID, std::forward<Args>(args)...);
}
    

Manager.hpp

#include "Entity.hpp"


class Manager
{
public:

    Manager();
    ~Manager();

    void add(Entity&& entity);
    void add(const std::string& name, Entity&& entity);

private:

    std::unordered_map<std::string, std::shared_ptr<Entity>> m_named_entities;

    std::vector<std::shared_ptr<Entity>> m_entities;

    Scene* m_scene_ref;
};

Scene.hpp


class Manager; // forward declaration of Manager

class Scene
{
public:
    
    // constructors, methods etc...

private:

    Manager entity_manager;
};

没有 Manager 类,一切都很好。当我尝试运行它时,VS 抛出错误:Error C2079 'Scene::entity_manager' uses undefined class 'Manager'

我无法弄清楚如何正确包含这些文件,以免它们产生链接错误(主要是因为链接循环)。此外,预定义类并不能解决问题。

当然,这段代码是“合法的”还是我做错了什么?

谢谢大家的回答

解决方案: 我通过将 Entity.hpp 到 Scene.hpp 的所有内容放在 Scene 类下来解决它

【问题讨论】:

  • 您是否尝试过向前声明一些类?这就是这个问题的解决方案。您可能还需要移动一些代码,以便在完全定义所有类之后定义方法。
  • @john 是的,我尝试做一些前向声明(在许多不同的组合中),但我每次都失败了。此外,我将我的方法保存在 .cpp 文件和模板中作为类定义下的内联。
  • 模板可能会改变一些事情,但如果没有具体的细节就很难提供帮助。除了前向声明(或重新设计类)之外,没有其他解决方案。有时它以一种实际的方式有所帮助,忘记单独的头文件。看看你是否可以编写一个头文件来声明所有三个类。
  • 请显示minimal reproducible example 以及您遇到的完整编译器错误
  • 您可能必须将标头拆分为类声明和模板方法定义。然后,您可以在模板方法定义之前包含所有类声明。任何需要比其他类的前向声明更多的东西都移到第二个头文件中。

标签: c++ linker include c++20


猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-11
  • 1970-01-01
  • 1970-01-01
  • 2010-12-11
  • 1970-01-01
  • 2014-06-02
  • 2012-01-04
相关资源
最近更新 更多