对' vtable '的未定义引用(最小示例)

undefined reference to `vtable (with minimal example)

本文关键字:未定义 vtable 引用      更新时间:2023-10-16

这可能是下一个重复,但是我没有在这段代码中找到错误:

#include <qwt_plot.h>
class QLinePlot : public QwtPlot
{
    Q_OBJECT
public:
    QLinePlot(QWidget* parent = 0, Qt::WindowFlags flags = 0): QwtPlot(parent)
    {
    }
    ~QLinePlot()
    {
    }
};

int main( int argc, char **argv )
{
    QLinePlot * plot = new QLinePlot();
}

我删除了构建文件夹,并再次运行qmake,但没有变化。错误信息是

test.cpp:7: undefined reference to `vtable for QLinePlot'

您的文件末尾缺少一个#include "test.moc":

// test.cpp
#include <qwt_plot.h>
class QLinePlot : public QwtPlot
{
    Q_OBJECT
public:
    using QwtPlot::QwtPlot;
};

int main( int argc, char **argv )
{
    QLinePlot plot;
}
#include "test.moc"

添加include行后,必须在项目上重新运行qmake。

你的例子不是最小的,但是。要重现这个问题,只需:

#include <QObject>
class Foo : public QObject {
  Q_OBJECT
  ~Foo() {}
}
int main() { Foo foo; }

你应该有你的QLinePlot类在头文件test.h。这样更简洁,而且您不需要在test.cpp中包含test.moc。例如

test.cpp

#include "test.h"
int main( int argc, char **argv )
{
  QLinePlot plot;
}

test.h

#include <qwt_plot.h>
class QLinePlot : public QwtPlot
{
   Q_OBJECT
   // stuff
};