如何禁止产生类对象呢?只要将类的构造函数用private修饰即可。
那么,如何限制类只能产生一个类对象呢?只要借助于友元函数的static对象即可。
示例代码如下:
1 class Printer
2 {
3 private:
4 Printer()
5 {
6 cout<<"thePrinter constructed"<<endl;
7 }
8 public:
9 void what()
10 {
11 cout<<"It's a printer"<<endl;
12 }
13 friend Printer & thePrinter();
14 };
15
16 Printer & thePrinter()
17 {
18 static Printer p;
19 return p;
20 }
这样一来,Printer类的对象就只有唯一的p,而且只有在首次调用thePrinter函数时才生成,不调用就不生成。
而将类的构造函数用private修饰还有另外一个作用:禁止类被继承。任何想要继承Printer的新类都不能顺利构造出对象来。
接下来就应该讨论限制类所能产生的对象数量为N(N>1)的情况了。不过在正式提出解决方案之前,首先来了解一下伪构造函数。
所谓伪构造函数就是类的一种static函数,它能够产生对象,作用就像构造函数。
之所以需要构造函数,是因为类真正的构造函数现已被private修饰,不能被外界调用。
仍然以Printer为例,删除友元函数thePrinter,为类添加static Printer* makePrinter()成员函数。
示例代码为:
1 class Printer
2 {
3 private:
4 Printer()
5 {
6 cout<<"thePrinter constructed"<<endl;
7 }
8 public:
9 void what()
10 {
11 cout<<"It's a printer"<<endl;
12 }
13 static Printer* makePrinter()
14 {
15 return new Printer();
16 }
17 };
如此定义的Printer类就没有生成对象数量上的限制了,但是它不允许被继承。makePrinter函数就是Printer类的伪构造函数。
认识了伪构造函数之后再回到之前的问题:如何限制类所能产生的对象数量为N(N>1)?
书中提出的方案是以上述伪构造函数为基础的,只要为Printer类添加一个计数就好了。
示例代码如下:
1 class Printer
2 {
3 private:
4 Printer()
5 {
6 cout<<"thePrinter constructed"<<endl;
7 }
8 static int counter;
9
10 public:
11 class TooManyObject
12 {
13 public:
14 void what()
15 {
16 cout<<"Too many Object"<<endl;
17 }
18 };
19 void what()
20 {
21 cout<<"It's a printer"<<endl;
22 }
23 static Printer* makePrinter()
24 {
25 if(++counter>10)
26 {
27 cout<<"Stop "<<endl;
28 exit(1);
29 }
30 return new Printer();
31 }
32 };
33 int Printer::counter=0;
上面代码实现出的Printer类被限制只能最多产生10个对象。
Good Good Study, Day Day Up.
顺序 选择 循环 坚持
原文链接: https://www.cnblogs.com/Braveliu/archive/2013/01/06/2847726.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/74647
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!