Qt编译错误:undefinedreferenceto`vtable for 。。。。'的解决

今天看1+1=2大牛的Qt文章中关于多线程的部分,于是自己想动手实现一下,没想到遇到这种问题undefinedreferenceto`vtable for 。。。。,蛋疼了一上午,也查了好多资料,那些资料比这个错误还难理解,有兴趣的请看这里http://www.examda.com/ncre2/cpp/fudao/20081219/085036477.html。

这个错误是在程序中添加了QOBJECT关键字以后出现的,但是我忽然想起,自己初学Qt时,按着那本官方教科书第二版写程序的时候怎么没遇到过呢,难道是因为我把所有代码都写到main.cpp中的缘故?嗯!就是这样!

整个解决过程如下:


开始我用Qt创建工程Test:在main.cpp中添加代码如下:

#include <QCoreApplication>
#include <QThread>
#include <QDebug>
#include <QObject>

class LongTimeAct: public QObject
{
    Q_OBJECT
public slots:
    void act();
};

class Begin:public QObject
{
    Q_OBJECT
signals:
    void sig();
public:
    void emiting();
};
void LongTimeAct::act()
{
    qDebug()<<"slot---My thread id is :"<<QThread::currentThreadId();
}


void Begin::emiting()
{
    qDebug()<<"sig---my thread id is :"<<QThread::currentThreadId();
    emit sig();
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    qDebug()<<"main---my thread id is :"<<QThread::currentThreadId();
    QThread thread;
    LongTimeAct act;
    Begin begin;
    act.moveToThread(&thread);
    QObject::connect(&begin,SIGNAL(sig()),&act,SLOT(act()));
    thread.start();
    begin.emiting();
    return a.exec();
}

一编译,便出现了题目中的那个错误,如下图:

Qt编译错误:undefinedreferenceto`vtable for 。。。。'的解决_第1张图片


于是我便又向工程中添加了一个test.h文件和一个test.cpp文件。然后把main.cpp中的代码分拆到这俩文件中。


test.h中的代码如下:

#ifndef TEST_H
#define TEST_H
#include <QObject>

class LongTimeAct: public QObject
{
    Q_OBJECT
public slots:
    void act();
};

class Begin:public QObject
{
    Q_OBJECT
signals:
    void sig();
public:
    void emiting();
};

#endif // TEST_H



test.cpp中的代码如下:

#include <QThread>
#include <QDebug>
#include "test.h"

void LongTimeAct::act()
{
    qDebug()<<"slot---My thread id is :"<<QThread::currentThreadId();
}


void Begin::emiting()
{
    qDebug()<<"sig---my thread id is :"<<QThread::currentThreadId();
    emit sig();
}


main.cpp中的代码如下:
#include <QCoreApplication>
#include <QDebug>
#include <QThread>
#include "test.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    qDebug()<<"main---my thread id is :"<<QThread::currentThreadId();
    QThread thread;
    LongTimeAct act;
    Begin begin;
    act.moveToThread(&thread);
    QObject::connect(&begin,SIGNAL(sig()),&act,SLOT(act()));
    thread.start();
    begin.emiting();
    return a.exec();
}



编译以后就成功了!!!!如下图:

Qt编译错误:undefinedreferenceto`vtable for 。。。。'的解决_第2张图片

可惜的是我只是解决了这个编译错误,但我不知道为什么这样做,因为我查了.pro文件,发现里面除了添加了头文件和cpp文件外跟原来没什么差别。

望路过的大牛指点一下为什么这样子做就可以避免这个编译错误了。不胜感激!

另外还有一点就是我最开始还遇到了collect2:ld returned 1 exit status错误,原因就是我语法不熟,我为了在发射信号时输出一句话自己定义了Begin类中的sig()函数,这个函数是信号函数,只能声明不能自己定义,Qt内部会处理,有关信号和槽的问题,详见http://blog.csdn.net/michealtx/article/details/6858784。要把它那句输出放到发射sig()信号的emiting()函数中emit sig();前面,详见test.cpp中的emiting()函数,如下代码是错误的:

void Begin::sig()
{
    qDebug()<<"sig---my thread id is :"<<QThread::currentThreadId();
}





   

你可能感兴趣的:(thread,多线程,Class,qt,Signal)