单例类-通过重载“新”运算符

单例类 -是一次仅在内存中存在一个对象的类。

我们可以使用以下方法创建单例类:

  • 静态方法或
  • 通过重载该类的“新”运算符。
这是通过重载该类的“ new”运算符来创建单例类的简单示例。

#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;
} 
附加的文件
档案类型:txt iSingleton.txt (1.0 KB,459视图)

From: https://bytes.com/topic/c/insights/942239-singleton-class-overloading-new-operator

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值