小编Ham*_*aro的帖子

无法使用dynamic_cast从Base转换为Derived

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

//基础和派生

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)

c++ polymorphism dynamic-cast game-engine

0
推荐指数
1
解决办法
398
查看次数

标签 统计

c++ ×1

dynamic-cast ×1

game-engine ×1

polymorphism ×1