以下代码是转载的。
觉得不错。
#include <iostream>
using namespace std;
class A
{
public :
static A*GetInstance()
{
if(count<=0)
{
return NULL;
}
count--;
return new A;
}
static void DeleteInstance(A* pInstance)
{
delete pInstance;
pInstance = 0;
}
private :
A() {}
~A() {}
static int count ;//实例化次数
};
int A::count=3;
void main()
{
A *f1 = A::GetInstance();
A *f2 = A::GetInstance();
A *f3 = A::GetInstance();
if (f3==NULL)
{
cout << "f3 NULL\n";
}
else
{
cout << "f3 Not NULL\n";
}
A *f4 = A::GetInstance();
if(f4==NULL)
{
cout << "f4 NULL\n";
}
A *f5 = A::GetInstance();
if(f5==NULL)
{
cout << "f5 NULL\n";
}
}