c++ - C++ - 如何返回协变类列表?
问题描述
我正在处理 Qt + C++ (x11)。
我有一个基类和几个返回指向该子类的新指针(协变)的子类。我也需要返回这些子类的容器(QList)。一个例子:
class A
{
public:
int id;
}
class B : public A
{
int Age;
};
class WorkerA
{
public:
virtual A *newOne() {return new A()};
virtual QList<A*> *newOnes {
QList<A*> list = new QList<A*>;
//Perform some data search and insert it in list, this is only simple example. In real world it will call a virtual method to fill member data overriden in each subclass.
A* a = this.newOne();
a.id = 0;
list.append(this.newOne());
return list;
};
};
class WorkerB
{
public:
virtual B *newOne() override {return new B()}; //This compiles OK (covariant)
virtual QList<B*> *newOnes override { //This fails (QList<B*> is not covariant of QList<A*>)
(...)
};
};
这将无法编译,因为 QList 是与 QList 完全不同的类型。但是类似的东西会很好。在现实世界中,B 会比 A 拥有更多的数据成员,并且会有 C、D...,因此需要对列表的返回进行“协变”。我会好很多:
WorkerB wb;
//some calls to wb...
QList<B*> *bList = wb.newOnes();
B* b = bList.at(0); //please excuse the absence of list size checking
info(b.id);
info(b.age);
比
WorkerB wb;
//some calls to wb...
QList<A*> *bList = wb.newOnes();
B* b = static_cast<B*>(bList.at(0)); //please excuse the absence of list size checking
info(b.id);
info(b.age);
有什么办法可以做到这一点?
解决方案
我希望从下面提到的代码中你会得到一些关于这个问题的提示。
这是main.cpp:
#include <QCoreApplication>
#include <QDebug>
#include "myclass.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MyClass mClass;
mClass.name = "Debussy";
// put a class into QVariant
QVariant v = QVariant::fromValue(mClass);
// What's the type?
// It's MyClass, and it's been registered
// by adding macro in "myclass.h"
MyClass vClass = v.value<MyClass>();
qDebug() << vClass.name;
return a.exec();
}
推荐阅读
- reactjs - Material-ui 自动完成警告 提供给自动完成的值无效。您可以使用 getOptionSelected` 属性自定义相等测试
- c# - 比较字符串变量并忽略外部空格
- python - 如何在python中提取文本的最后一部分
- rest - 无法使用 golang 测试和 beego 框架验证具有预期输出的 Http 响应
- javascript - Why is this function definition ignored?
- node.js - 使用for循环在nodejs中运行多个post请求不起作用
- dji-sdk - 获取速度并计算加速度 DJI SDK
- android - 如何以编程方式更改wifi代理android?
- python - 如何使用python在pdf文件中查找发票表的区域坐标?
- r - 追加到数据表列时将字符保持为单行