对函数发送的未定义引用

undefined reference to function send

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

我是C++/Qt编程的新手。我制作了这个简单的对话框来检查 QLineEdit,如果输入的文本是"bob",则应启用"确定"按钮。我无法让它成功编译,它给了我:

dialog.cpp|31|undefined reference to `Dialogmio::send()'

我做错了什么?

这是dialog.h:

//dialog.h
#ifndef DIALOG_H_INCLUDED
#define DIALOG_H_INCLUDED
#include <QDialog>
class QPushButton;
class QLineEdit;
class Dialogmio : public QWidget

{

public:
Dialogmio(QWidget *parent =0);
signals:
void send ();
public slots:
void recip(QString &text);

private:
QLineEdit *linedit;
QPushButton *buttonOK;

};
#endif

这是对话框.cpp:

//dialog.cpp
#include <QtGui>
#include "dialog.h"
Dialogmio::Dialogmio(QWidget *parent)
: QWidget(parent)
{
linedit = new QLineEdit();
buttonOK = new QPushButton("OK");
buttonOK->setEnabled(FALSE);

connect( linedit, SIGNAL( textChanged(const QString &) ), this, SLOT( recip(const QString &) ));
connect (this,SIGNAL( send()), this, SLOT( buttonOK->setEnabled(true)) );
QHBoxLayout *layout = new QHBoxLayout();
layout->addWidget(linedit);
layout->addWidget(buttonOK);
setLayout(layout);

}
void Dialogmio::recip(QString &text)
{
QString a = linedit->text();
if (a == "bob"){
emit send();   //here it gives me the error
}
}

这是主要的.cpp:

#include <QApplication>
#include "dialog.h"

int main(int argc, char* argv[])
{
QApplication app(argc, argv);
Dialogmio *dialog = new Dialogmio;
dialog->show();
return app.exec();
}

我已经按照建议插入了Q_OBJECT宏,现在我在第 7 行又出现了一个错误:

dialog.cpp|7|undefined reference to `vtable for Dialogmio'|

你首先包括QDialog的Qt文件,但随后继续从QWidget继承。虽然从QWidget继承不是问题,但你打算实际从QDialog(?)继承,在这种情况下,你应该这样定义你的类:-

class Dialogmio : public QDialog
{
    Q_OBJECT
    public:
        Dialog(QWidget* parent);
    private slots:
        void aSlotFunction();
}

信号和插槽机制是Qt独有的C++扩展,为了使类使用它,该类必须包含Q_OBJECT宏,这增加了所有必要的功能。在构建阶段,Qt解析标头并创建扩展所需的代码,包括运行时类型信息,动态属性系统,当然还有信号和插槽。

正如您声明使用代码块作为 IDE 时,如果它在构建之前没有自动运行 qmake,则每当向类添加任何信号或插槽以使 moc(元对象编译器)看到它们时,都需要执行此操作。

另一件事是连接信号和插槽的调用是错误的:-

connect (this,SIGNAL( send()), this, SLOT( buttonOK->setEnabled(true)) );

SLOT 宏中的参数采用插槽功能,因此您需要创建一个插槽并将其连接到发送信号:-

connect(this, SIGNAL(send()), this, SLOT(aSlotFunction());

在aSlotFunction中,您可以调用为按钮启用的集合:-

void Dialogmio::aSlotFunction()
{
    buttonOK->setEnabled(true);
}

如果您使用的是Qt 5,则处理连接的语法更简单:-

connect(this, &Dialogmio::send, this, &Dialogmio::aSlotFunction);

由于此语法接受指向将要调用的函数的指针,因此实际上不必将它们声明为槽才能工作。此外,您不提供参数,因此如果它们发生更改,您也不必更新连接调用。