gpt4 book ai didi

c++ - 将派生类型转换为基类型

转载 作者:行者123 更新时间:2023-11-28 02:54:37 25 4
gpt4 key购买 nike

我正在尝试学习从基类到派生类的类型转换。此示例将向您展示我正在尝试做的事情。我知道这不是一个有效的解决方案。我只是想为我的软件创建一个动态架构,并愿意接受建议和解决方案。

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;
}

那么由于性能或任何其他原因,这是一个不错的选择吗?会不会有很多类,很多类型?

最佳答案

虽然我不同意你的整体设计,但这里是如何修复你的解决方案:

使用 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;
}

关于c++ - 将派生类型转换为基类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22282929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com