博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
设计一个类只能生成该类的一个实例
阅读量:2719 次
发布时间:2019-05-13

本文共 1314 字,大约阅读时间需要 4 分钟。

class Singleton{public:    Singleton()    {        if (_count == 0)        {            cout << "进行构造函数" << endl;            _count++;        }        else        {            cout << "构造失败" << endl;        }    }private:    static int _count;};int Singleton::_count=0;void test(){    Singleton t1;    Singleton t2;}int main(){    test();    system("pause");    return 0;}
//只适用于单线程,多线程需要加锁class Singleton{public:    static Singleton* GetConstuct()    {        if (instance == NULL)        {            instance = new Singleton();            return instance;        }        return NULL;    }private:    static Singleton* instance;    Singleton()    {            cout << "进行构造函数" << endl;    }};Singleton* Singleton::instance = NULL;void test(){    Singleton* t1 = Singleton::GetConstuct();    Singleton* t2= Singleton::GetConstuct();}int main(){    test();    system("pause");    return 0;}
利用静态构造函数,初始化静态变量的时候创建实例class Singleton{public:    static Singleton* GetConstuct()    {        return instance;    }private:    Singleton()    {        cout << "进行构造函数" << endl;    }    static Singleton* instance;};Singleton* Singleton::instance = new Singleton();void test(){    Singleton* t1 = Singleton::GetConstuct();    Singleton* t2 = Singleton::GetConstuct();}int main(){    test();    system("pause");    return 0;}

转载地址:http://kqstd.baihongyu.com/

你可能感兴趣的文章
struts2 验证框架原理及实例
查看>>
Struts2 异常处理
查看>>
ecplise 使用 git
查看>>
Android开发之如何保证Service不被杀掉(broadcast+system/app)
查看>>
java蓝桥杯试题特殊文字
查看>>
centos 搭建基本环境 jdk+mysql
查看>>
AIX下安装proFTPD-支持虚拟用户和SFTP
查看>>
Jmeter性能测试内部分享
查看>>
Mysql日常使用维护命令总结
查看>>
【非Web工程】Spring + C3P0 + Hibernate + Mysql
查看>>
如何领取无敌李笑来老师的免费糖果
查看>>
导入ecplise项目No projects are found to import解决方案
查看>>
多线程写入文件笔试题
查看>>
BeanFactoryPostProcessor的使用
查看>>
多线程自增运算的原子性与可见性分析
查看>>
TPC,TPCC,TPMC(计算机性能衡量指标) -----
查看>>
别错过!漂亮又好用的思维导图模板
查看>>
如何有效地进行资料整理?
查看>>
项目管理高手常用的10种图表!
查看>>
EasyUI之multiple多选框禁用某些项选中
查看>>