2
好的,所以我对Qt和C++都很陌生。我试图用QMetaType与我自己的类,我不能让它与子类一起工作。下面是我有(有很可能吨的问题,不好意思):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中不做任何事情(只是开放括号,右括号))这里是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退出。
非常感谢。
非常感谢!我感到很傻。 – JohnJamesSmith0