【问题标题】:Undefined reference to constructor when using QT [duplicate]使用 QT 时对构造函数的未定义引用 [重复]
【发布时间】:2017-04-28 11:47:40
【问题描述】:

我是 C++ 编程和 QT 的新手。

我想测试 Qt 插槽和信号,看看它们是如何工作的。我有一个名为myclass.h 的头文件,其中包含以下代码:

#ifndef MYCLASS_H
#define MYCLASS_H
#include <QObject>
#include <QString>
class myclass: public QObject
{
   Q_OBJECT
   public:
     myclass(const QString &text, QObject *parent=0);
     const QString& text() const;
     int getlengthoftext() const;
   public slots:
     void settext(const QString &text);
   signals:
     void changedtext(const QString&);
     private:
     QString m_text;
};

还有一个带有 class_mine 名称的文件,代码如下:

#include "myclass.h"
#include <QObject>
#include <QString>
void myclass::settext(const QString &text)
{
     if (m_text==text)
        return;
     m_text =text;
     emit changedtext(m_text);
} 
#endif

在我的主文件中我有这个:

#include "mainwindow.h"
#include <QApplication>
#include "myclass.h"
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    // MainWindow w;
    // w.show();
    QObject parent;
    myclass *a1 , *b , *c;
    a1=new myclass("foo" , &parent);
    b=new myclass("bar" , &parent);
    c=new myclass("baz" , &parent);
    QObject::connect(a1,SIGNAL(changedtext(const QString&)),
    b,SLOT(settext(const QString&)));
    QObject::connect(b,SIGNAL(changedtext(const QString&)),
    c,SLOT(settext(const QString&)));
    QObject::connect(c,SIGNAL(changedtext(const QString&)),
    b,SLOT(settext(const QString&)));
    b->settext("text");
    return a.exec();
}

我不知道为什么会出现此错误:

main.cpp:13: 错误: 对 `myclass::myclass(QString const&, QObject*)' 的未定义引用

【问题讨论】:

  • 初学C++并不是学习QT的好条件
  • 我想支持@TheTechel 所说的话。一方面,Qt 很大,需要时间来掌握;你有效地在两条战线上作战。其次,Qt 以一种非常特殊的方式使用 C++,这与推荐的现代 C++ 实践相距甚远。我建议您在研究 Qt 之前先更牢固地掌握 C++(例如来自 good book)。使用 Qt,您希望能够评估它的哪些实践值得在您的代码中遵循,哪些最好与它的 Qt 交互部分隔离。
  • 感谢您的推荐,但我必须同时学习它们。

标签: c++ qt class signals-slots


【解决方案1】:

在 myclass.h 中定义你的构造函数

myclass(const QString &text, QObject *parent=0) { /* your code here */ };

或在 myclass.cpp 中

myclass::myclass(const QString &text, QObject *parent) { /* your code here */ };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-08
    • 2020-07-07
    • 1970-01-01
    • 2015-03-01
    • 1970-01-01
    • 2017-02-02
    相关资源
    最近更新 更多