[英]Cast QList of derived to QList of base
I have these classes:我有这些课程:
class IParameter {};
class ModuleParameter : public IParameter {};
Now I have QList of derived:现在我有派生的 QList:
QList<ModuleParameter*> list;
When I cast single item it's ok:当我投射单个项目时,没关系:
IParameter *p = list[0]; // ok
When I cast the list I've got an error.当我投射列表时,我遇到了错误。
QList<IParameter*> *list = static_cast<QList<IParameter*>*>(&list);
Invalid static_cast from type QList<ModuleParameter*>* to type QList<IParameter*>*
. Invalid static_cast from type QList<ModuleParameter*>* to type QList<IParameter*>*
。
So, how can I cast?那么,我该如何投呢?
If you really want a QList<IParameter*>, you can do something like these:如果你真的想要一个 QList<IParameter*>,你可以做这样的事情:
QList<A*> la;
QList<B*> lb;
...
std::transform(lb.cbegin(),
lb.cend(),
std::back_inserter(la),
[=](B* b)
{
return static_cast<A*>(b);
});
QList
is a template without common base class type and QList<ModuleParameter*>
is a type unrelated to QList<IParameter*>
, you can't access QList<ModuleParameter*>
polymorphically through a pointer to QList<IParameter*>
. QList
是不常见的基类型和模板QList<ModuleParameter*>
是一类无关QList<IParameter*>
则无法访问QList<ModuleParameter*>
多晶型通过一个指向QList<IParameter*>
What you trying to do is impossible to do this way.你试图做的事情是不可能以这种方式做到的。
Instead you may store pointers to ModuleParameter
in QList<IParameter*>
and use cast when accessing them.相反,您可以将指向ModuleParameter
指针存储在QList<IParameter*>
并在访问它们时使用 cast。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.