未定义对`vtable for MainWindow'的引用

Ala*_* M. 4 c++ eclipse qt

我正在遵循Qt的使用指南QPushButton

我确实按照指南的建议进行了操作,但出现编译错误:

./src/mainwindow.o: In function `MainWindow::MainWindow(QWidget*)':
mainwindow.cpp:(.text+0x1d): undefined reference to `vtable for MainWindow'
./src/mainwindow.o:mainwindow.cpp:(.text+0x25): more undefined references to `vtable for MainWindow' follow
collect2: error: ld returned 1 exit status
make: *** [HelloWorldProj] Error 1
Run Code Online (Sandbox Code Playgroud)

我尝试添加析构函数:

~MainWindow(){};
Run Code Online (Sandbox Code Playgroud)

但是问题仍然存在。

我没有声明任何虚函数,除了里面的一个函数QMainWindow(我继承自的类):

virtual QMenu *createPopupMenu();
Run Code Online (Sandbox Code Playgroud)

是否应该在我的课程中定义?

Dum*_*ene 6

您需要设置CMAKE_AUTOMOCON我们CMake的文件。

# Instruct CMake to run moc automatically when needed.
set(CMAKE_AUTOMOC ON)
Run Code Online (Sandbox Code Playgroud)

“ AUTOMOC目标属性控制cmake是否检查目标中的C ++文件以确定它们是否需要运行moc,并创建规则以在适当的时间执行moc。” - 参考


CJC*_*ink 5

尝试在项目上运行 qmake,然后进行重建。

你的例子坏了(如果可能,我会尽快更新)

创建一个空文件并将其命名为 PushButtonExample.pro 并添加以下内容:

QT       += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = PushButtonExample
TEMPLATE = app

SOURCES += main.cpp \
    mainwindow.cpp

HEADERS  += mainwindow.h
Run Code Online (Sandbox Code Playgroud)

然后qmake在该文件上运行,然后make.

我还建议您下载 Qt Creator 并将其用作构建 Qt 项目时的 IDE。大多数 Qt 安装还安装了 Qt Creator IDE,它有一些很好的示例和向导来创建新项目。

确保所有 4 个文件都在同一个文件夹中

main.cpp
mainwindow.cpp
mainwindow.h
PushButtonExample.pro
Run Code Online (Sandbox Code Playgroud)

在命令行中,导航到该文件夹​​并运行 qmake

qmake PushButtonExample.pro
Run Code Online (Sandbox Code Playgroud)

这应该在同一文件夹中创建以下文件

Makefile
Run Code Online (Sandbox Code Playgroud)

然后运行 make

这应该构建示例,最后运行应用程序:

./PushButtonExample
Run Code Online (Sandbox Code Playgroud)

(我也在更新维基页面)