64,654
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
using namespace std;
class Singleton
{
protected:
Singleton() {cout<<"con of Singleton"<<endl;}
~Singleton(){cout<<"dcon of Singleton"<<endl;}
//Singleton(const Singleton& s);///只定义,不实现
public:
static Singleton * getInstance()
{
if(_instance==0)
{
_instance = new Singleton();
}
return _instance;
}
///other class functions...
void show()
{
cout<<"This is a Singleton !"<<endl;
}
private:
static Singleton * _instance;
///other class members ...
class Proxy
{
public:
~Proxy()
{
if(_instance!=0)
{
delete _instance;
_instance = 0;
}
}
};
static Proxy pt;
};
///静态成员的初始化
Singleton* Singleton::_instance = 0;//new Singleton();
Singleton::Proxy Singleton::pt;
int main()
{
Singleton *s=Singleton::getInstance();
s->show();
Singleton *a=Singleton::getInstance();
a->show();
cout<<(a == s)<<endl;
Singleton c(*s);///compile error: 'Singlenton::~Singlenton() is protected'
c.show();
return 0;
}