我正在尝试从基类到派生类学习类型转换。此示例将向您显示我要执行的操作。我知道这不是一个有效的解决方案。我只是想为我的软件创建一个动态架构,并打开建议和解决方案。
enum EComponentType
{
Base = 0,
Material = 1
};
class FComponent
{
public:
FComponent() { m_type = EComponentType::Base; }
EComponentType type() { return m_type; }
protected:
EComponentType m_type;
};
class FMaterial : public FComponent
{
public:
FMaterial() { m_type = EComponentType::Material; }
void setValue(int value) { m_value = value; }
int value() { return m_value; }
private:
int m_value;
};
int main(int argc, char *argv[])
{
FMaterial material;
material.setValue(22);
QVector<FComponent> Components;
Components << material;
for (int i = 0; i < Components.size(); i++)
{
switch (Components[i].type())
{
case EComponentType::Material:
FMaterial material = (FMaterial)(Components[i]); // --> invalid of course
int value = material.value();
break;
}
}
return 0;
}
更新1:
int main(int argc, char *argv[])
{
QVector<FComponent*> Components;
FMaterial material;
material.setValue(22);
Components << &material;
for (int i = 0; i < Components.size(); i++)
{
switch (Components[i]->type())
{
case EComponentType::Material:
FMaterial *m = static_cast<FMaterial*>(Components[i]);
int value = m->getValue();
qDebug() << value;
break;
}
}
return 0;
}
由于表现或任何其他原因,这是一个不错的选择吗?会有很多课程和很多类型?
答案 0 :(得分:2)
虽然我不同意您的整体设计,但这里是如何解决您的解决方案:
使用static_cast
代替dynamic_cast
,它会起作用。 dynamic_cast
如果你将至少一个虚函数放到基类中它也会有效,但是它的类型过多会与你的类型枚举一起冗余。
编辑:我还注意到你试图投射值,如果是类,你必须在类指针或引用上进行转换!
class FComponent
{
public:
// Withtout this if you delete an FComponent* then the destructor of the derived class isn't called.
virtual ~FComponent() {}
};
class FMaterial : public FComponent
{
};
int test()
{
QVector<FComponent*> Components;
FMaterial* material = new FMaterial;
Components << material;
for (int i = 0; i < Components.size(); i++)
{
switch (Components[i].type())
{
case EComponentType::Material:
FMaterial* material = static_cast<FMaterial*>(Components[i]);
int value = material->value();
break;
}
}
// Somewhere later in your code....
for (int i = 0; i < Components.size(); i++)
delete Components[i];
// TODO: remove all deleted pointers from Components
return 0;
}