单例类 -是一次仅在内存中存在一个对象的类。
我们可以使用以下方法创建单例类:
- 静态方法或
- 通过重载该类的“新”运算符。
#include<iostream.h>
#include<conio.h>
#include<alloc.h>
class iSingleton
{
static iSingleton *sptr; //this pointer points to object of the class
public:
iSingleton() //public constructor
{
sptr=this;
}
void *operator new(size_t); //overload new operator for class which is to be made iSingleton.
};
iSingleton *iSingleton::sptr=NULL; //initialize pointer to NULL
void *iSingleton::operator new(size_t s)
{
if(sptr!=NULL) //if already one object is created return reference to same object
return sptr;
else
return malloc(s); //else allocate memory for one (first) object
}
int main()
{
clrscr();
iSingleton *sptr1=new iSingleton; //first object created
iSingleton *sptr2=new iSingleton; //second object created
if(sptr1==sptr2)
cout<<"\nGiven class is a Singleton class.";
else
cout<<"\nGiven class is not a Singleton class.";
getch();
return 0;
}
From: https://bytes.com/topic/c/insights/942239-singleton-class-overloading-new-operator