【问题标题】:Class with virtual function, when derived from QObject, leads to linking error具有虚函数的类,当从 QObject 派生时,会导致链接错误
【发布时间】:2011-08-18 07:41:08
【问题描述】:

以下是可以正常工作的代码

class HttpService {
public:
    virtual ~HttpService(); // implemented in .cpp
protected:
    HttpService(struct MHD_Connection *conn) {}
};
class HttpFileService : public HttpService
{
public:
    virtual ~HttpFileService() ; // implemented in .cpp
protected:
    HttpFileService(struct MHD_Connection *conn) : HttpService(conn) {}
};

现在,当我将HttpService 设为QObject 的派生类时,如下所示:

#include <QObject>                      // change #1
class HttpService  : public QObject {   // change #2
    Q_OBJECT                            // change #3
public:
    virtual ~HttpService();
protected:
    HttpService(struct MHD_Connection *conn) {}
};

class HttpFileService : public HttpService {
    Q_OBJECT                            // change #4
public:
    virtual ~HttpFileService() ;
protected:
    HttpFileService(struct MHD_Connection *conn) : HttpService(conn) {}
};

我遇到以下链接错误:

Undefined symbols for architecture x86_64:
  "vtable for HttpService", referenced from:
      HttpService::~HttpService()in httpservice.o

HttpService 的构造函数更改为以下也无济于事

explicit HttpService(QObject *parent = 0) : QObject(parent)

【问题讨论】:

  • ~HttpService() 代码更改后仍然在.cpp 文件中实现?我问这个是因为,在更改后的代码中,我没有看到 // implemented in .cpp 的注释。
  • @iammilind,是的,它仍然是。唯一更改的行在 cmets 中突出显示
  • 这就是HttpService() 的全部内容吗?如果我在抽象基类中声明一个虚函数,而忘记将其设为纯函数,我经常会看到此错误。 (gcc 在与第一个非纯、非内联虚函数相同的目标文件中生成 vtable,如果声明了这样的函数,并且如果没有定义,那么它将最终丢失)。
  • @mike-seymour,好点子!这确实不是全班,但我仔细检查了你所说的,这里似乎不是这样。另外,为什么代码在从 QObject 派生之前不会中断?

标签: c++ qt linker ld


【解决方案1】:

强制运行 qmake 看看是否有效。

【讨论】:

    【解决方案2】:

    您是否链接到正确的 qt 库?

    【讨论】:

    • 是的,我的项目中还有其他 QObject 派生类正在顺利完成
    【解决方案3】:

    你在调用 moc 编译器吗?如果没有,请删除 Q_OBJECT 宏!你是否包含/链接来自 moc 编译的结果?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-24
      • 2013-08-25
      • 2013-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-01
      相关资源
      最近更新 更多