c++单列模式学习
简单的说,一个类只能生成一个对象,看看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,但在程序运行的时候有且只有一个对象。
6666 谢谢大牛 6666666666 谢谢大佬 感谢楼主分享 好的,非常感谢
页:
[1]