【Qt】一个简单的C++单例模式示例

本文介绍了一种使用C++实现的单例模式,并通过两个具体类实例展示了如何确保类只有一个实例并提供全局访问点。文章包括了Test类和SingleInstance类的具体实现,以及main函数中的使用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

单例类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
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值