元类型和继承

QMetaType and inheritance

本文关键字:继承 类型      更新时间:2023-10-16

好的,所以我是Qt和c++的新手。我试图将QMetaType与我自己的类一起使用,但我无法让它与子类一起工作。以下是我的资料(可能有很多问题,抱歉):

testparent.h:

#include <QMetaType>
class TestParent
{
public:
    TestParent();
    ~TestParent();
    TestParent(const TestParent &t);
    virtual int getSomething(); // in testparent.cpp, just one line returning 42
    int getAnotherThing();      // in testparent.cpp, just one line returning 99
};
Q_DECLARE_METATYPE(TestParent)

test1.h:

#include <QMetaType>
#include "testparent.h"
class Test1 : public TestParent
{
public:
    Test1();
    ~Test1();
    Test1(const Test1 &t);
    int getSomething();          // int test1.cpp, just one line returning 67
};
Q_DECLARE_METATYPE(Test1)

…(除非另有说明,此处声明的所有成员都被定义为在testparent.cpp或test1.cpp中不做任何事情(只是开括号、闭括号)。

#include <QtGui/QApplication>
#include "test1.h"
#include "testparent.h"
#include <QDebug>
int main(int argc, char *argv[])
{
    int id = QMetaType::type("Test1");
    TestParent *ptr = new Test1;
    Test1 *ptr1 = (Test1*)(QMetaType::construct(id));
//    TestParent *ptr2 = (TestParent*)(QMetaType::construct(id));
    qDebug() << ptr->getSomething();
    qDebug() << ptr1->getSomething();     // program fails here
//    qDebug() << ptr2->getAnotherThing();
//    qDebug() << ptr2->getSomething();
    delete ptr;
    delete ptr1;
//    delete ptr2;
    return 0;
}

正如你所看到的,我试图用ptr2测试出一些多态性的东西,但后来我意识到ptr1甚至不起作用。(编辑:前一句没有意义。哦,好吧,问题解决了(编辑:nvm它确实有意义))当我运行这是第一个qDebug打印67时,会发生什么,如预期的那样,然后它会卡住几秒钟,最终退出代码-1073741819。

Type必须注册!宏观的Q_DECLARE_METATYPE是不够的。你在main函数的开头少了一行

qRegisterMetaType<Test1>("Test1");

现在您可以获得不为零的id(这意味着类型已注册):

int id = QMetaType::type("Test1");