设计一个特殊的类,该类只能在堆上创建对象
将类的析构函数声明为private,但是为了创建该类的对象,则必须提供创建对象和释放对象的接口,用static函数成员实现:
class HeapOnly
{
public:
static HeapOnly *CreateInstance()
{
HeapOnly *obj = new HeapOnly;
obj->m = 9;
return obj;
}
static void DeleteInstance(HeapOnly *obj)
{
if (obj != NULL)
delete obj;
}
private:
HeapOnly(){};
~HeapOnly(){};
public:
int m;
};
int main()
{
HeapOnly *obj = HeapOnly::CreateInstance();
cout << obj->m << endl;
HeapOnly::DeleteInstance(obj);
system("pause");
return 0;
}
设计一个类,该类只能在栈上创建对象
在堆上创建对象要用到new,为了在类外不能使用new,delete,把new,delete重载为私有:
class StackOnly
{
public:
StackOnly()
{
cout << "constructor." << endl;
}
~StackOnly()
{
cout << "destructor." << endl;
}
private:
void* operator new(size_t size);
void operator delete(void* ptr);
};
int main()
{
StackOnly s;
system("pause");
return 0;
}
设计一个类,该类只能创建一个对象
类实例化对象时,需要检查是否已经存在同类对象,所以需要静态成员变量;另外还要提供对外的全局访问方式,故需要静态方法来创建与销毁该实例对象:
class singleton
{
public:
static singleton* getpsin()
{
if (psin == NULL)
{
psin = new singleton();
}
return psin;
}
static void relice()
{
if (psin != NULL)
{
delete psin;
}
psin = NULL;
}
private:
singleton()
{
cout << "+++++" << endl;
}
static singleton* psin;
};
singleton* singleton::psin = NULL;
int main()
{
singleton *p = singleton::getpsin();
system("pause");
return 0;
}