当我尝试将基类转换为派生类时出现错误。 我想访问我放在我的组件 vector 中的派生类。
//基础和派生
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
vector 的对象,Component
Material
的一部分将被存储。这个问题被称为 object slicing problem .
您可能想要制作一个 vector ,其中包含指向基本多态类的指针。
::std::vector<::std::unique_ptr<Componenet>> components;
还有dynamic_cast
很昂贵,因此您可能只想在存储返回值后调用它:
T * const test = dynamic_cast<T*>(components[i].get());
if(test)
{
return test;
}
关于c++ - 不能使用 dynamic_cast 从 Base 转换为 Derived,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48290103/