More Effective C++ (限制类的对象数量)

如何禁止产生类对象呢?只要将类的构造函数用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.

顺序  选择  循环  坚持

 

 

 

posted @   kaizenly  阅读(481)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
打赏

喜欢请打赏

扫描二维码打赏

微信打赏

点击右上角即可分享
微信分享提示