我刚刚开始使用 Qt 框架进行编程。下面是一个非常简单的程序:
#include <QtCore/QCoreApplication>
#include <QDebug>
class MyClass : public QObject
{
Q_OBJECT
public:
MyClass() {}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MyClass *c = new MyClass();
return a.exec();
}
但是当我尝试编译和运行它时收到以下错误:
在函数 MyClass
中:
对 MyClass 的 vtable
的 undefined reference
但是当我删除 QObject 宏时,一切正常。请注意,该类定义在与主函数相同的文件中。
我正在使用 Qt 4.7 版,在 Win 7 上运行。
是什么导致了这个问题?
更新: 当我在一个单独的头文件中定义我的类时,我得到了同样的错误。我的定时器.h:
#ifndef MYTIMER_H
#define MYTIMER_H
#include <QtCore>
class MyTimer : public QObject
{
Q_OBJECT
public:
QTimer *timer;
MyTimer();
public slots:
void DisplayMessage();
};
#endif // MYTIMER_H
我的定时器.cpp:
#include "mytimer.h"
#include <QtCore>
MyTimer::MyTimer()
{
timer = new QTimer();
connect(timer,SIGNAL(timeout()),this,SLOT(DisplayMessage()));
timer->start(1000);
}
void MyTimer::DisplayMessage()
{
qDebug() << "timed out";
}
这是 main.cpp:
#include <QtCore/QCoreApplication>
#include <QDebug>
#include "mytimer.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MyTimer *mt = new MyTimer();
return a.exec();
}
最佳答案
您需要使用 qmake 编译它,这将为您的自定义 QObject 类创建模拟方法。参见 here关于生成 moc 文件的更多信息。
由于您的示例不包含头文件,因此不会对其进行解析,也不会生成任何 moc 文件。您需要在单独的头文件中声明 MyClass,并运行 moc 生成工具。
关于C++/Qt Q_OBJECT宏导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9929269/