【问题标题】:undefined reference to `vtable (with minimal example)对 `vtable 的未定义引用(带有最小示例)
【发布时间】:2016-10-25 20:04:42
【问题描述】:

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

#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'

【问题讨论】:

  • 最上面的相关链接是stackoverflow.com/questions/1552069/…,这看起来确实与该链接完全相同。如果不是,并且如果您理解那里给出的答案,您能否编辑您的问题以解释您的问题为何不同?
  • 你在 cpp 中有类定义吗?如果是,请将其移至标题..
  • @H.G 在那种情况下,你提出了一个很好的观点,我的立场是正确的。
  • 可能无法链接所需的库
  • @H.G. moc 处理任何有效的 C++ 源代码。标头在任何方面都不是特别的:通常所有.h.cpp 文件都应该是有效的C++,除非你搞砸了或者正在做一些宏元编程技巧。因此,您可以通过 moc 传递 .h.cpp。并且要表明foo.cpp 中有可移动的内容,您需要在文件末尾附加#include "foo.moc"。就这样。然后重新运行qmake 就可以了!

标签: c++ qt


【解决方案1】:

您的文件末尾缺少#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; }

【讨论】:

  • 我更喜欢带有头文件和 cpp 文件的解决方案,但由于我只使用 cpp 文件,这是正确的解决方案。
  • 如果 QObject-deriving 类在一个源文件中本地使用,将其推送到它自己的标题可能没有什么意义 - 然后你会想要包含 moc 输出.cpp 文件的结尾 :)
【解决方案2】:

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

test.cpp

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

测试.h

#include <qwt_plot.h>
class QLinePlot : public QwtPlot
{
   Q_OBJECT

   // stuff
};

【讨论】:

    猜你喜欢
    • 2012-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多