设计一个类,只能实现1个实例或3个实例

/*********************************************
题目:	1)设计一个类,我们只能生成该类的一个实例
	2)设计一个类,只能生成该类的3个实例
******************************************/
//1)
#include<iostream>
using namespace std;
class CSingleton  
{  
    public:  
    static CSingleton * GetInstance()  
    {  
        if(NULL == m_pInstance)  
            m_pInstance = new CSingleton();  
        return m_pInstance;  
    }  
    static void Release()   //必须,否则会导致内存泄露  
    {  
        if(NULL != m_pInstance)  
        {  
            delete m_pInstance;  
            m_pInstance = NULL;  
        }  
    }  
      
    protected:  
        CSingleton()  
        {  
            cout<<"CSingleton"<<endl;  
        };  
        static CSingleton * m_pInstance;  
};  
CSingleton* CSingleton::m_pInstance = NULL; 

int main(){
	CSingleton* pSingleton1 =  CSingleton::GetInstance();
	CSingleton* pSingleton2 =  CSingleton::GetInstance();
	if(pSingleton1 == pSingleton2)
	{
		cout << "Produced one instance !"<<endl;
		pSingleton1->Release();
	}
	else
	{
		cout << " Produced two instances !"<<endl;
		pSingleton1->Release();
		pSingleton2->Release();
	}

	return 0;
}
为了防止从类的外部调用构造函数,产生类的新的实例,我们应该把该类的构造函数声明成protected或者private。
由于只能生成一个类的实例,我们可以考虑用静态成员函数来记录,到底之前有没有构造过类的实例。如果没有构造过,那么就构造一个新的实例。

如果构造过,那么就把之前构造的那个实例返回。为了保证之前构造的实例,在程序运行期间一直存在,不被析构,我们只能把指向这个实例的指针声明成静态变量,

存放在静态存储区,把这个类的实例用new来构造,并放在堆里。

//2)
#include<iostream>
using namespace std;
class finalclass
{
public: static int count;
public:
	static finalclass *getinstance()
	{
		if(count <= 0)
			return NULL;
		count--;
		return new finalclass;
	}
	static void setcount(int n)
	{
		count = n;
	}
private:
	 finalclass(){}
	~finalclass(){}
};
int finalclass::count = 0;
int main()
{
	 finalclass::setcount(3);
	 finalclass *f1 = finalclass::getinstance();
	 finalclass *f2 = finalclass::getinstance();
	 finalclass *f3 = finalclass::getinstance();
	 if(f3 == NULL)
		  printf("f3 NULL\n");
	else
		 printf("f3 NOT NULL\n");
	finalclass *f4 = finalclass::getinstance();
	if(f4 == NULL)
		 printf("f4 NULL\n");
	finalclass *f5 = finalclass::getinstance();
	if(f5 == NULL)
		printf("f5 NULL\n");
}

参考:http://www.cppblog.com/dyj057/archive/2005/09/20/346.html

http://www.2cto.com/kf/201304/202169.html

mark:

http://www.cnblogs.com/08shiyan/archive/2012/03/16/2399617.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值