用c++设计一个类,这个类只能被实例化3次,且不能被继承

// only3Instance.cpp : 定义控制台应用程序的入口点。
//通过此实例实现一个类,这个类不能被继承,并且最多可以实例化3次

//在设计模式中,有一种模式叫“单例模式”,这个模式向我们展现了一个类,这个类只产生一个实例
//这个类里面,屏蔽掉了拷贝构造函数,构造函数,析构函数,这样这个类就不会被继承,因为我们
//知道,当一个类被继承时,子类必须先调用父类的构造函数,在析构时,父类最后被析构,将创建对象的部分定义为一个静态对象,所以只会产生一个实例
//下面我们仿照这一思路,改变对象“静”的特性,就可以随心所欲的创建对象,同时我们在堆上定义一个变量(static),用来检验
//对象创建的个数

#include "stdafx.h"
#include <process.h>
#include <iostream>
using namespace std;

 

 


class CFinalClass
{
public:
 static CFinalClass* GetInstance()
 {
  if (m_index>=m_count)
  {
   return NULL;
  }
  m_index++;
  return new CFinalClass();
 }
 static void SetCount(int n)
 {
  m_count=n;
 }
private:


 static int m_index;
 static int m_count;


private://将构造函数和析构函数定义为私有的,这样就不会被继承
 CFinalClass()
 {

 }
 ~CFinalClass()
 {

 }
};

 

 


int CFinalClass::m_index=0;
int CFinalClass::m_count=0;

 

 

 

int _tmain(int argc, _TCHAR* argv[])
{

 
 CFinalClass::SetCount(3);
 CFinalClass *p1=CFinalClass::GetInstance();
 CFinalClass *p2=CFinalClass::GetInstance();
 CFinalClass *p3=CFinalClass::GetInstance();
 CFinalClass *p4=CFinalClass::GetInstance();
 CFinalClass *p5=CFinalClass::GetInstance();

 if (p1==NULL)
 {
  cout<<"p1 is null"<<endl;
 }
 else
 {
  cout<<"p1 is not null"<<endl;
 }

 if (p2==NULL)
 {
  cout<<"p2 is null"<<endl;
 }
 else
 {
  cout<<"p2 is not null"<<endl;
 }

 if (p3==NULL)
 {
  cout<<"p3 is null"<<endl;
 }
 else
 {
  cout<<"p3 is not null"<<endl;
 }
 cout<<"-----------------------------------------"<<endl<<endl;
 if (p4==NULL)
 {
  cout<<"p4 is null"<<endl;
 }
 if (p5==NULL)
 {
  cout<<"p5 is null"<<endl;
 }
 system("pause");
 return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值