>一书中的条款26,那里有很详细的描述,这里不再讲解。下面来看看代码是如何实现的。">
菜鸟笔记
提升您的技术认知

一个具有对象计数功能的基类-ag真人游戏

  参考<>一书中的条款26:"限制某个class所能产生的对象数量",参照"一个用来计算对象个数的基类"中的代码,简单的将里面的代码实现。一个具有对象计数功能的基类,简单来说,就是完成一个base class,作为对象计数之用,并让诸如printer之类的class继承它。更多内容请参考<>一书中的条款26,那里有很详细的描述,这里不再讲解。下面来看看代码是如何实现的。

  代码如下:

#include "stdafx.h"
#include 
using namespace std;
//一个具有对象计数功能的基类
template<class beingcounted>
class counted
{
public:
    class toomanyobjects{};   //定义一个异常类
    static int objectcount()
    {
        return numobjects;
    }
protected:
    counted();
    counted(const counted& rhs);
    ~counted()
    {
        cout<<"销毁第 "<" 个实例"<<endl;
        --numobjects;
    }
private:
    static int numobjects;           //当前产生实例的个数
    static const size_t maxobjects;  //可以产生实例的最多个数
    void init();
};
template<class beingcounted>
counted::counted()
{
    init();
}
template<class beingcounted>
counted::counted(const counted& rhs)
{
    init();
}
template<class beingcounted>
void counted::init()
{
    if (numobjects >= maxobjects)  //产生的实例大于最大值就抛出异常
    {
        throw toomanyobjects();
    }
    cout<<"构造第 "<1<<" 个实例"<<endl;
      numobjects;
}
//继承自具有对象计数功能的基类
class printer : private counted
{
public:
    static  printer* makeprinter();
    static  printer* makeprinter(const printer& rhs);
    ~printer();
    using counted::objectcount;      //使基类的objectcount()在子类可见
    using counted::toomanyobjects;   //使基类的toomanyobjects在子类可见
private:
    printer();
    printer(const printer& rhs);
};
template<class beingcounted>
int counted::numobjects;
const size_t counted::maxobjects = 5;   //最多5个

printer::printer()
{
}
printer::~printer()
{
}
printer::printer(const printer& rhs)
{
}
printer* printer::makeprinter()
{
    return new printer;
}
printer* printer::makeprinter(const printer& rhs)
{
    return new printer(rhs);
}
int _tmain(int argc, _tchar* argv[])
{
    printer *p1 = printer::makeprinter();
    printer *p2 = printer::makeprinter();
    printer *p3 = printer::makeprinter(*p1);
    printer *p4 = printer::makeprinter(*p2);
    printer *p5 = printer::makeprinter();
    delete p4;
    delete p5;
    p4 = printer::makeprinter();
    p5 = printer::makeprinter();
    try
    {
        p1 = printer::makeprinter(); //printer产生的实例大于5,则抛出异常
    }
    catch (printer::toomanyobjects)
    {
        cout<<"toomanyobjects"<<endl;
    }
    delete p1;
    delete p2;
    delete p3;
    delete p4;
    delete p5;
    cout<<"剩余实例为:"<endl;
return 0; }

  运行界面如下:

                                      

网站地图