【问题标题】:Returning a child class from a parent class array C++从父类数组 C++ 返回子类
【发布时间】:2022-11-17 09:50:26
【问题描述】:
class Component {
    // Code here
};

class TransformComponent : public Component {
    // Code here
};

class Entity:
    public:
        Component components[25];
        
        TransformComponent *getTransform() {
            for(int i = 0; i < 25; i++) {
                if(typeid(components[i]) == typeid(TransformComponent())) {return *(components + i);}
            }
        }
};

我有一个组件数组,里面可以是“组件”的任何子类,比如“TransformComponent”。问题是,在编译时,计算机认为组件数组只填充了“组件”对象。该函数应该返回一个“TransformComponent”,并且编译器认为这是一个错误,即使我返回的数组中的元素是一个 TransformComponent。有什么解决办法吗(最好是简单的)?

【问题讨论】:

    标签: c++ arrays function loops oop


    【解决方案1】:

    '我有一个组件数组,里面可以是“组件”的任何子类,比如“TransformComponent”。 - 这种说法是错误的。如果您有一个 Component 对象数组,那么在数组中的每个索引处,都有一个 Component 类型的对象,而不是后代。

    如果您想存储多个(例如 Base-Descendants)类型,您有两个主要选择:

    • 使用(智能)指针容器:std::vector&lt;std::unique_ptr&lt;Component&gt;&gt; components
    • 使用变体:std::vector&lt;std::variant&lt;Component, TransformComponent/*, ... other types*/&gt; components&gt;

    【讨论】:

      猜你喜欢
      • 2014-04-01
      • 1970-01-01
      • 2021-04-28
      • 1970-01-01
      • 2018-03-11
      • 1970-01-01
      • 2010-11-04
      • 2021-07-07
      相关资源
      最近更新 更多