【问题标题】:Creating simple object in Qt 5.7 C++在 Qt 5.7 C++ 中创建简单对象
【发布时间】:2016-09-16 11:58:39
【问题描述】:

我有以下问题:

我想从主函数中的类创建对象。看起来这是一个链接器问题。您有什么想法,这个错误消息的原因可能是什么?

它的错误信息是:

main.obj:-1: error: LNK2019: Verweis auf nicht aufgelöstes externes Symbol ""public: __thiscall Test::Test(class QString)" (??0Test@@QAE@VQString@@@Z)" in函数“_main”。

main.obj:-1: error: LNK2019: Verweis auf nicht aufgelöstes externes Symbol ""public: __thiscall Test::~Test(void)" (??1Test@@QAE@XZ)" in Funktion "_main" .


debug\Wth.exe:-1: 错误:LNK1120: 2 nicht aufgelöste Externe

我有一个非常简单的类测试:

test.h

#ifndef TEST_H
#define TEST_H
#include <QtCore/QObject>

class Test
{
public:
    Test(QString name);
   ~Test();

private:
    QString m_name;
};

#endif // TEST_H

那么 .cpp 文件如下所示:

test.cpp

#include "test.h"

Test::Test(QString st) : m_name(st){}
Test::~Test(){}

非常基本,在我的主要功能中:

main.cpp

#include <QCoreApplication>
#include "test.h"


int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    Test t("lam");
    return a.exec();
}

【问题讨论】:

  • 什么不起作用?
  • sry,我已经发布了错误消息,上面写着:引用未解析的外部符号
  • 你确定 test.cpp 文件被编译了吗?
  • 也许你应该重建你的代码。请在重建之前运行 qmake 并清理项目,

标签: c++ qt oop object


【解决方案1】:

您可能正在寻找有关创建 QObject 类的示例。

让我们扩展您的代码:

#ifndef TEST_H
#define TEST_H
#include <QtCore/QObject>

class Test : public QObject
{
  // Allways add the Q_OBJECT macro 
  Q_OBJECT
public:
    // Use a null default parent
    explicit Test(const QString& name, QObject* parent = 0);
   ~Test();

private:
    QString m_name;
};

#endif // TEST_H

在您的 cpp 文件中:

#include "test.h"

Test::Test(const QString& st, QObject* parent) : QObject(parent), m_name(st {}
Test::~Test(){}

在你的 main.cpp 中没有

#include <QCoreApplication>
#include "test.h"


int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    Test t("lam");
    return a.exec();
}

这应该可行。如果您有链接问题,请执行一些步骤:

  1. 运行 qmake(在您的项目文件夹中使用 qt 创建者的上下文菜单)
  2. 清理您的项目
  3. 再次重建

【讨论】:

    【解决方案2】:

    结果是我必须先运行 qmake。我正在做的事情是在构建而不是在运行。

    谢谢大家,只是花了很多时间。我是 Qt 的新手。

    【讨论】:

      【解决方案3】:

      现在您在main.cpp 中包含test.h,但test.h 没有任何地方引用test.cpp 实现。因此,您必须在 test.h 的底部包含 test.cpp 或将其包含在编译器调用中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-17
        • 1970-01-01
        • 2017-01-16
        • 1970-01-01
        • 1970-01-01
        • 2016-10-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多