元类型和继承
QMetaType and inheritance
好的,所以我是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");
相关文章:
- 继承模板类中的类型别名
- 在运行时检查继承是否只有一种类型和 void*
- 如何正确消除继承类型定义的歧义?以及如何简化他们的创作?
- 如何从C 中的集合中检索多个继承类型
- 从模板继承<类型名 T、T 最大值、T 最小值>具有多个类型名模板参数的结构
- 继承类型的指针之间的静态强制转换
- 指向具有继承类型的类数据成员的指针
- 继承类型强制
- 可以从模板化的智能指针仅继承类型类吗
- 仅通过从其他类继承类型来定义类型
- 如果继承类型受到保护,我可以制作基类的指针以指向派生对象吗?
- std::tuple,按继承类型获取项
- 调用具有继承类型的基类函数
- 继承c++类型保护
- 如何在c++中更改继承类型的访问类型
- 二叉树,其中数据是不同的继承类型
- 继承类型定义
- 使用' void_t '检测多个继承类型重复错误
- 删除继承类型
- 构造函数在私有继承类型之外可用