主线程类声明定义如下:
Http_Get.h:
#pragma once
#include <QtWidgets/QMainWindow>
#include "ui_Http_Get.h"
#include "post_thread_test.h"//此处包含了子线程类
#include<QtNetwork/QNetworkReply>
#include <QJsonObject>
#include<QJsonArray>
#include<QJsonDocument>
#include <QSslConfiguration>
#include <QtNetwork/QNetworkAccessManager>
#include <QString>
#include <QDebug>
#include <QVector>
#include <QFile>
#include <QDateTime>
#include <QDir>
#include <QString>
#include <QTime>
#include <QThread>
#include <QCoreApplication>
class Http_Get : public QMainWindow
{
Q_OBJECT
public:
Http_Get(QWidget *parent = Q_NULLPTR);
~Http_Get();
private:
Ui::Http_GetClass ui;
void test_thread();
void friend_function();
QNetworkAccessManager *accessManager;
QJsonObject jsonObject;
QJsonDocument jsonDoc;
QNetworkRequest request;
QString ip_ad;
QVector<Post_v> post_con;
Post_v temp_post;
QThread *post_thread;
post_thread_test* mythreadT;//声明线程类
signals:
void ex_post_thread(QVector<QString>*);
};
Http_Get.cpp:
void Http_Get::test_thread()
{
mythreadT->test_a = 10.58;//访问子线程中的私有变量
mythreadT->moveToThread(post_thread);
post_thread->start();
emit ex_post_thread(thread_vec);
}
子线程类声明如下:
post_thread_test.h:
#pragma once
#include <QObject>
#include <QThread>
#include <QVector>
#include <QString>
#include <QDebug>
#include<QtNetwork/QNetworkReply>
#include <QJsonObject>
#include<QJsonArray>
#include<QJsonDocument>//json
#include <QSslConfiguration> //https
#include <QtNetwork/QNetworkAccessManager>
#include <QTime>
#include <QCoreApplication>
//#include "Http_Get.h"//此处不可以包含主线程的头文件,否则会报错
class post_thread_test : public QObject
{
Q_OBJECT
friend class Http_Get;
//friend void Http_Get::friend_function();会报错
public:
post_thread_test(QObject *parent = Q_NULLPTR);
~post_thread_test();
void post_collect(QVector<QString>*);
private:
double test_a = 0;//可以在主线程类中访问该私有变量
};
此时可以在主线程(Http_Get)中访问子线程(post_thread_test)私有变量。但主线程和子线程的头文件不可以相互包含(post_thread_test.h不可以包含#include "Http_Get.h"),然而在子线程中依然可以设置主线程类为友元类。但如果想设置主线程中的成员函数为友元函数(friend void Http_Get::friend_function();)则不可以。此处应该如何在主线程类和子线程类中相互引用头文件?