【问题标题】:getter and setter with header file c++带有头文件c ++的getter和setter
【发布时间】:2022-06-11 22:55:06
【问题描述】:

Getter 和 Setter 方法在 Qt 线程中不起作用。

我从主函数中设置了QString 值,我想从QThread 中获取该值。

我的代码

ma​​in.cpp

#include "networkthread.h"
#include <QCoreApplication>
#include "msg.h"
#include <QString>

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

    QString str = argv[1];

    QString strb = argv[2];

    msge myObj;
    myObj.setstra(str);

    myObj.setstrb(strb);

    NetworkThread networkThread;

    networkThread.start();
    int result = a.exec();

    networkThread.requestInterruption();
    networkThread.exit();
    networkThread.wait(2000);

    return 0;
}

msg.h

#include <iostream>
#include <QString>
using namespace std;

class msge
{
private:
    QString stra;
    QString strb;

public:
    void setstra(QString s)
    {
        stra = s;
    }

    QString getstra()
    {
        return stra;
    }

    void setstrb(QString s)
    {
        strb = s;
    }

    QString getstrb()
    {
        return strb;
    }
};

networkthread.cpp

#include "networkthread.h"
#include "msg.h"
#include <QDebug>
#include <QString>
#include <iostream>
#include <QCoreApplication>

void NetworkThread::run()
{

    while (!isInterruptionRequested())
    {
        msge myObj;
        QString str = myObj.getstra();
        QString strb = myObj.getstrb();
        qDebug() << str + "str first";
        qDebug() << strb + "str second";
        break;
    }

    QCoreApplication::quit();
}

networkthread.h

#ifndef NETWORKTHREAD_H
#define NETWORKTHREAD_H

#include <QThread>
#include <QString>

class NetworkThread : public QThread
{
public:
    void run();

private:
};

#endif // NETWORKTHREAD_H

输出

C:\Users\prade\Documents\untitled2\release>untitled2 hello hai
"str first"
"str second"

getter 方法不起作用。

我做错了什么?

我该如何解决这个问题?

【问题讨论】:

  • 你有两个对象。一个你调用 setter,另一个你调用 getter
  • 仅仅因为两个msge myObj;具有相同的名称并不能神奇地使它们成为同一个对象
  • 如果没有QThread,您将获得相同的输出
  • 你能详细解释一下吗?

标签: c++ qt qthread


【解决方案1】:

NetworkThread 中创建一个新的msge 对象

void NetworkThread::run()
{

  while(!isInterruptionRequested()) {

 msge myObj;   <<<<<<<<<<<<<<<
 
 QString str = myObj.getstra();

这是一个不同于您在 ma​​in.cpp 中调用 setter (setstra()) 的对象。

ma​​in.cpp 中的msge myObj; 无论如何都不会被使用或传递给NetworkThread

您需要将您的值传递给NetworkThread 对象,并首先调用其版本的 msge 对象的设置器。

【讨论】:

  • 能详细解释一下吗?
  • 还是找不到答案?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-17
  • 1970-01-01
相关资源
最近更新 更多