吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 2148|回复: 7
收起左侧

[C&C++ 转载] c++单列模式学习

[复制链接]
52lxw 发表于 2019-10-8 10:47
本帖最后由 52lxw 于 2019-10-8 10:49 编辑

简单的说,一个类只能生成一个对象,看看c++是怎么实现的。
image.png
image.png

代码:
[C++] 纯文本查看 复制代码
// study.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>

using        namespace std;

class CSingleton
{

private:
        CSingleton();
        static        CSingleton        *pInstance;
public:
        static        CSingleton*        GetInstance(){
                if (pInstance == NULL){
                        pInstance = new CSingleton();
                        return pInstance;
                }
                return pInstance;
        }
        void        Address()
        {
                printf("%08x\n", pInstance);
        }
        ~CSingleton();
};

CSingleton::CSingleton()
{
}

CSingleton::~CSingleton()
{
}

CSingleton* CSingleton::pInstance = NULL;
int _tmain(int argc, _TCHAR* argv[])
{
        
        auto        a = CSingleton::GetInstance();
        auto        b = CSingleton::GetInstance();
        a->Address();
        b->Address();

        getchar();
        return 0;
}


虽然调用了两次GetInstance,但在程序运行的时候有且只有一个对象。
image.png

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

禁闭岛 发表于 2019-10-8 11:19
谢谢楼主分享,请问这是哪本书上的?
ayaoko 发表于 2019-10-8 11:25
网瘾少年徐志摩 发表于 2019-10-8 11:43
roboger 发表于 2019-10-8 12:16
支持中 厉害了
by海洋 发表于 2019-10-8 13:27
不懂,这个是初学者看的吗
Zurdo 发表于 2019-10-11 21:48
①私有化:拷贝构造,静态变量(内部维护指针使用),构造函数 都进行私有化。
②公共方法:设置静态的接口方法。
③静态变量初始化(一般是在某个作用于下)。
④使用(类名::接口方法名)的方式创建对象。
ccitllz 发表于 2019-11-18 22:19
禁闭岛 发表于 2019-10-8 11:19
谢谢楼主分享,请问这是哪本书上的?

同问!我也想知道是什么书的截图
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-4-27 05:06

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表