无法使用dynamic_cast从Base转换为Derived

Ham*_*aro 0 c++ polymorphism dynamic-cast game-engine

当我尝试将基类转换为派生类时,我收到错误.我想访问我放在组件向量中的派生类.

//基础和派生

class Component
{
public:
    Component();
    virtual ~Component();
private:
};

class Material:public Component{...};
Run Code Online (Sandbox Code Playgroud)

//在主要

int textureID = gameScene.gameObjects[0].getComponent<Material>()->texture;
Run Code Online (Sandbox Code Playgroud)

//游戏对象

#pragma once
#include <vector>
#include "Component.h"

class GameObject:public Component
{
public:
    GameObject();
    GameObject(int otherAssetID);
    ~GameObject();

    int assetID;
    std::vector<Component> components;

    void addComponent(Component otherComponent);
    void deleteComponent(Component otherComponent);

    template <class T>
    T* getComponent() {
        for (int i = 0; i < components.size(); i++)
        {
            if (dynamic_cast<T*>(components[i]) != nullptr)
            {
                T *test = dynamic_cast<T*>(components[i]);
                return test;
            }
        }

        return nullptr;
    }
private:

};
Run Code Online (Sandbox Code Playgroud)

use*_*670 5

std::vector<Component>不能包含除Component自身以外的类的对象.如果Material向向量添加对象,则将存储该Component部分Material.这个问题被称为对象切片问题.

您可能希望创建一个包含指向基本多态类的指针的向量.

::std::vector<::std::unique_ptr<Componenet>> components;
Run Code Online (Sandbox Code Playgroud)

dynamic_cast很贵,所以你可能只想在存储返回值时调用它:

 T * const test = dynamic_cast<T*>(components[i].get());
 if(test)
 {
     return test;
 }
Run Code Online (Sandbox Code Playgroud)