简体   繁体   English

C++ - 如何返回协变类列表?

[英]C++ - How to return list of covariant classes?

I'm dealing with Qt + C++ (x11).我正在处理 Qt + C++ (x11)。

I have a base class, and several subclasses that return a new pointer to that subclass (covariant).我有一个基类和几个返回指向该子类(协变)的新指针的子类。 I need to return too, an container (a QList) of these subclasses.我也需要返回这些子类的容器(QList)。 An example:一个例子:

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*>)
        (...)
        };        
};

This will fail to compile, because QList is a completely different type from QList.这将无法编译,因为 QList 是与 QList 完全不同的类型。 But something similar would be nice.但类似的东西会很好。 In real world, B will have more data members than A, and there will be C, D..., hence the need of "covariantate" the return of list.在现实世界中,B 的数据成员将比 A 多,并且会有 C、D...,因此需要“协变”列表的返回。 I will be much nicer:我会更好:

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

than

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

Is there any way to achieve this?有没有办法实现这一目标?

I hope from below mention code you will get some hint for this issue.我希望从下面提到的代码中你会得到一些关于这个问题的提示。

Here is main.cpp:这是 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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM