【问题标题】:How do I access subclass variables in a baseclass vector? (for an entity component system)如何访问基类向量中的子类变量? (对于实体组件系统)
【发布时间】:2020-09-15 19:53:41
【问题描述】:

所以我有一个带有“组件”的向量。我可以从向量轻松访问组件变量,但是当我向向量添加子类时,我无法访问这些变量。

也许这是一个非常大胆的问题,解决方案可能非常复杂,但我不知道从哪里开始以及尝试什么,因此感谢任何帮助。

struct Component {};
std::vector<Component> components;

struct Transform : Component
{
    int x, y;
};

void Start()
{
    components.push_back(Transform());
    //can't acces x below
    std::cout << components[0].x;
}

解决方案

只为唯一指针创建向量:

std::vector<std::unique_ptr<Component>> components;

第 2 步:

void Start()
{   
    //add component (pointer to vector)
    components.push_back(std::make_unique<Transform>());
    //cast to Transform
    Transform const* transform = static_cast<Transform*>(components[0].get());

    std::cout << transform->x;
}

【问题讨论】:

  • 发生对象切片,你可能想要std::vector&lt;std::unique_ptr&lt;Component&gt;&gt; components; 或std::variant。
  • 感谢您的回答!那么现在如何添加到向量中? “components.push_back(Transform());”不再起作用了,因为向量需要一个指针,对吗?如何向向量添加“std::unique_ptr”?

标签: c++ inheritance vector entity


【解决方案1】:

首先你有一个对象切片的问题,排序你可以做类似的事情:

struct Component {};
std::vector<std::unique_ptr<Component>> components;

struct Transform : Component
{
   int x = 0, y = 0;
};

void Start()
{
    components.push_back(std::make_unique<Transform>());
}

至于访问Transform 的成员,您有几个选择。 C++ 已内置 rtti 但请注意它的速度很慢:

Transform const* transform = dynamic_cast<Transform*>(components[0].get());
if(transform != nullptr)
    std::cout << transform.x;

另一种选择是从Component 实现一个虚函数:

struct Component
{
    virtual void Update();
};

struct Transform : public Component
{
    int x = 0, y = 0;
    virtual void Update() override
    {
        std::cout << x;
    }
};

void Start()
{
    components.push_back(std::make_unique<Transform>());
    for(Component& component : components)
    {
        component.Update();
    }
}

【讨论】:

  • 我喜欢动态转换的想法,但它给了我这个错误:运行时 dynamic_cast 的操作数必须具有多态类类型
  • @Felix 您必须修复对象切片错误才能使其正常工作。
  • 不是动态转换,而是静态转换!然后一切正常。
  • @Felix static_cast 也可以。但它有点挑剔,如果你最终将 static_cast 转换为 Transform 并且你投射的组件实际上是其他东西,例如 Render,那么你将调用 UB。
【解决方案2】:

问题是,您的向量存储类 Component 的对象。 push_back 中发生的情况是,该向量创建一个新的 Component,它是从您的 Transform() 对象复制。

所以这里要注意的第一件大事是,您并没有真正将Transform 对象推入向量中,因此没有这样的.x。

请注意,在 C++ 中,只有 Transform x{}; 行会在堆栈上创建一个对象。因此Component y=x; 创建另一个对象并从x 复制其数据(在这种情况下没有,因为Component 为空)。
这基本上就是您的代码中发生的事情,只是在向量中隐藏了一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-05
    • 2013-01-16
    • 2013-07-24
    • 1970-01-01
    • 2011-09-05
    • 2016-01-30
    • 1970-01-01
    • 2018-08-15
    相关资源
    最近更新 更多