您的位置:首页 > 其它

一个具有对象计数功能的基类

2017-12-21 15:36 211 查看
源自more effective c++ item M26:

目的:

为了做到一个类具有对类对象数量限制功能及不再派生新的子类;做法是继承一个计数功能的基类,并将自身构造私有化。过程是Printer在进行构造的时候,会先进行基类的构造,在构造时会调用init()函数,函数会判定是否已经到达限制,若到达限制就进行throw,否则就继续进行构造。

代码:

#include<iostream>
#include<exception>
#include<Error.h>
using namespace std;

template <typename BeingCounted>
class Counted{
public:
class TooMany :public exception{//抛异常
public:
TooMany():exception("the number is enough...."){}
};
static int objectCount(){return numobject;}//声明静态确保所有对象共享
protected:
Counted();
Counted(const Counted &rhs);
~Counted(){--numobject;}
private:
static int numobject;
static const size_t maxobject;
void init();//使用init统一调配,避免构造语句的重复

};

template<typename BeingCounted>
Counted<BeingCounted>::Counted(){
init();
}
template<typename BeingCounted>
Counted<BeingCounted>::Counted(const Counted&rhs){
init();
}
template<typename BeingCounted>
void Counted<BeingCounted>::init(){
if(numobject>=maxobject)throw TooMany();
++numobject;
}

class Printer:private Counted<Printer>{
public:
static Printer*makePrinter();//使用静态伪构造方法禁止Printer派生出新的子类
static Printer*makePrinter(const Printer&rhs);
~Printer();
void submitJob(const Printer&job);
void reset();
void performSelfTest();
using Counted<Printer>::objectCount;
using Counted<Printer>::TooMany;//使TooMany在Printer中权限的为public
private:
Printer();
Printer(const Printer&rhs);
};
Printer *Printer::makePrinter(){
return new Printer;
}
Printer*Printer::makePrinter(const Printer&rhs){
return new Printer(rhs);
}
Printer::Printer(){
}
Printer::Printer(const Printer&rhs){
}
const size_t Counted<Printer>::maxobject=3;//const static对象需要在类外进行初始化。
int Counted<Printer>::numobject=0;

int main(void){
try{
Printer *p1=Printer::makePrinter();
cout<<"build success..."<<endl;
Printer*p2=Printer::makePrinter(*p1);
cout<<"build
9e5a
success..."<<endl;
Printer*p3=Printer::makePrinter();
cout<<"build success..."<<endl;
Printer*p4=Printer::makePrinter();
cout<<"build success..."<<endl;
}
catch(Printer::TooMany &me){
cout<<me.what();
}
system("pause");
return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐