在Qt 5.7 c++中创建简单对象

Creating simple object in Qt 5.7 C++

本文关键字:创建 简单 单对象 c++ Qt      更新时间:2023-10-16

我有以下问题:

我想在main函数中从类创建对象。看起来是连接器的问题。您知道这个错误消息的原因是什么吗?

它的错误信息是:

主要。obj:-1:错误:LNK2019: Verweis auf夜aufgelöstes外部符号"public: __thiscall Test::Test(类QString)"(? ? 0 test@@qae@vqstring@@@z)";in function "_main"

主要。obj:-1:错误:LNK2019: Verweis auf夜aufgelöstes外部符号"public: __thiscall Test::~Test(void)"(? ? 1 test@@qae@xz)";in function "_main"


debugWth.exe:-1:错误:LNK1120: 2夜aufgelöste外部

我有一个非常简单的Class Test:

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函数中我有:

main.cpp

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

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    Test t("lam");
    return a.exec();
}

您可能正在寻找一个关于创建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(){}

No in your 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. 重新构建

所以我必须先运行qmake。我所做的就是建造,然后跑。

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

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