1、跟C、C++那样用extern
2、新建一个类,存放全局的变量(使用全局变量这里举例就是第二种方法)
定义
student.h
#ifndef STUDENT_H
#define STUDENT_H
#include <QString>
/* 新建类 学生信息 */
class Student
{
public:
Student();
~Student(){}
QString id; /* 学号 */
const static QString idDefault;/* 默认学号 */
};
#endif // STUDENT_H
student.cpp
#include "student.h"
#include <QDebug>
const QString Student::idDefault = "1300810434";/* 学号默认值 */
Student::Student()
{
id = Student::idDefault;/* 赋id默认值 */
qDebug()<<"Student id"<< id ;
}
info.h
#ifndef IN_FO_H
#define IN_FO_H
#include "student.h"
/* 信息类包含学生信息 */
class Info
{
public:
Info();
static Student stu;/* 学生信息 */
/* 其他信息 老师、医生*/
};
#endif // AC_PANEL_H
info.cpp
#include "info.h"
#include <QDebug>
Student Info:: stu;/* 全局变量、函数放到stu这个类中 */
Info::Info()
{
Info::stu.id= "202000810434";/* 更改学生信息 */
qDebug()<<"Info id"<< Info::stu.id;/* 打印更改后学生信息 */
}
使用
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "info.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->label->setText(Info::stu.id);/* 两种信息显示方式label、qDebug */
qDebug() << "MainWindow id"<< Info::stu.id ;
}
MainWindow::~MainWindow()
{
delete ui;
}
main.cpp
#include "mainwindow.h"
#include <QApplication>
#include "info.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Info info;/* 信息实例化 */
MainWindow w;
w.show();
return a.exec();
}