[英]Cannot use dynamic_cast to convert from Base to Derived
当我尝试将基类转换为派生类时出现错误。 我想访问放置在组件向量中的派生类。
//基础和派生
class Component
{
public:
Component();
virtual ~Component();
private:
};
class Material:public Component{...};
//在主
int textureID = gameScene.gameObjects[0].getComponent<Material>()->texture;
//游戏对象
#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:
};
std::vector<Component>
不能包含Component
本身以外的其他类的对象。 如果将Material
对象添加到矢量,则将存储Material
的Component
部分。 该问题称为对象切片问题 。
您可能想要创建一个包含指向基多态类的指针的向量。
::std::vector<::std::unique_ptr<Componenet>> components;
dynamic_cast
也很昂贵,因此您可能只想在存储返回值后调用它:
T * const test = dynamic_cast<T*>(components[i].get());
if(test)
{
return test;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.