单实例的模式

使用技术:构造函数私有+静态对象指针+静态成员函数(其中判断指针,使得时时刻刻,只存在着一个的对象)

#include <iostream>

class Singleton
{
public:
~Singleton(){}

static Singleton* GetSingleton();
private:
Singleton(){};

static Singleton* pTHIS;
};

Singleton* Singleton::pTHIS = NULL;

Singleton* Singleton::GetSingleton()
{
if (!pTHIS) pTHIS = new Singleton();

return pTHIS;
}



int main()
{
using namespace std;

//Singleton* pImpossible = new Singleton(); //compile error
//Singleton aImpossible; //compile error

Singleton* pOne = Singleton::GetSingleton();
Singleton* pTwo = Singleton::GetSingleton();

cout<<"Address of pOne: "<<pOne<<endl;
cout<<"Address of pTwo: "<<pTwo<<endl;


system("pause");
return 0;
}

你可能感兴趣的:(null,System,Class,iostream)