|
|
禁止求评分、诱导评分、互刷评分、互刷悬赏值,违规者封号处理。
禁止发布推广、邀请码、邀请链接、二维码或者有利益相关的任何推广行为。
所有非原创软件请发布在【精品软件区】,发帖必须按照本版块版规格式发帖。
简单的说,一个类只能生成一个对象,看看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,但在程序运行的时候有且只有一个对象。
|
|