单例类Test
#pragma once
#include <qwidget.h>
class Test :
public QWidget
{
public:
static Test& instance()
{
static Test test;
return test;
}
void set(int a, int b)
{
c = a;
d = b;
}
void get(int& a, int& b)
{
a = c;
b = d;
}
private:
int c=0;
int d=0;
Test() {}
Test(const Test&) {}
Test& operator==(const Test&) {}
};
SingleInstance单例类
#pragma once
#include <QtWidgets/QMainWindow>
#include "ui_SingleInstance.h"
class SingleInstance : public QMainWindow
{
Q_OBJECT
public:
SingleInstance(QWidget *parent = Q_NULLPTR);
static SingleInstance& instance()
{
static SingleInstance qinstance;
return qinstance;
}
private:
Ui::SingleInstanceClass ui;
};
main.cpp
#include "SingleInstance.h"
#include <QtWidgets/QApplication>
#include "Test.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Test::instance().set(3,5);//此处将Test类中的c、d设置为3、5
SingleInstance::instance().show();
return a.exec();
}
SingleInstance.cpp
#include "SingleInstance.h"
#include <qpushbutton.h>
#include "Test.h"
#include <qmessagebox.h>
#include <qdebug.h>
SingleInstance::SingleInstance(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
int a=0, b=0;
Test::instance().get(a,b);
qDebug() << "a:" << a << " b:" << b << endl;//此处打印3,5
}