简体   繁体   English

带有头文件c ++的getter和setter

[英]getter and setter with header file c++

Getter and Setter method not working in Qt thread. Getter 和 Setter 方法在 Qt 线程中不起作用。

I set QString value from main function and I want to get that value from QThread .我从 main 函数设置QString值,我想从QThread获取该值。

My codes我的代码

main.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味精.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网络线程.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网络线程.h

#ifndef NETWORKTHREAD_H
#define NETWORKTHREAD_H

#include <QThread>
#include <QString>

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

private:
};

#endif // NETWORKTHREAD_H

output输出

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

the getter method not worked. getter 方法不起作用。

What I did wrong in this?我在这方面做错了什么?

How can I solve this?我该如何解决这个问题?

In NetworkThread you create a new msge objectNetworkThread创建一个新的msge对象

void NetworkThread::run()
{

  while(!isInterruptionRequested()) {

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

This is a different object than you called the setters ( setstra() ) on in main.cpp .这是一个与您在main.cpp中调用 setter ( setstra() ) 不同的对象。

The msge myObj; msge myObj; in main.cpp is not used or passed to NetworkThread in anyway.无论如何, main.cpp中的内容都不会被使用或传递给NetworkThread

You will need to pass your values to the NetworkThread object and call the setters on its version of the msge object first.您需要将您的值传递给NetworkThread对象,并首先在其 msge 对象的版本上调用 setter。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM