c++ - QMetaType 和继承

标签 c++ qt inheritance qt4 introspection

好的,所以我对 Qt 和 C++ 都不熟悉。我正在尝试使用 QMetaType与我自己的类,我不能让它与子类一起工作。这是我所拥有的(可能有很多问题,抱歉):

测试父类.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 中不执行任何操作(仅打开括号,关闭括号))这是 main.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 退出。

非常感谢。

最佳答案

必须注册类型!宏 Q_DECLARE_METATYPE 是不够的。 您在 main 函数的开头缺少一行:

qRegisterMetaType<Test1>("Test1");

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

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

关于c++ - QMetaType 和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7061416/

相关文章:

c++ - 并行推回 vector 的 vector

c++ - 将 long int 转换为 void *

java - Java Class类的getMethod函数是如何工作的?

java - 组合语法对 Java 有用吗?

java子类有方法返回它的类

c++ - 如何在 C++ 中获取 int 中特定位置的编号?

c++ - 在 C++ 中管理控制台游标操作的简单且可移植的方法

c++ - 阻塞等待异步 Qt 信号

qt - 配置 qmake 以将安装头文件安装到不同的子文件夹

c++ - 将 QRegExValidator 用于 QLineEdit