more effective c++计算限制对象个数(21)

封装的基类很好++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
template<calss BeingCounted>
class Counted {
public:
class TooManyObjects{};
static int objectcount() {return numObjects;}
protect:
Counted();
Counted(const Counted& rhs);
~Counted() {--numObjects;}
private:
static int numObjects;
static const size_t maxobjects;
void init();
};
template<class BeingCounted>
Counted<BeingCounted>::Counted()
{init();}
template<class BeingCounted>
Counted<BeingCounted>::Counted(const Counted<BeingCounted>&)
{init();}
template<class BeingCounted>
void Counted<BeingCOunted>::init()
{
if (numObjects >= maxObjects) throw TooManyObjects();
++numobjects;
}
派生类很好:
class Printer: Private Counted<Printer> {
public:
static Printer* MakePrinter();
static Pritner* makePrinter(const Printer& rhs);
~Printer
..............
..........
using Counted<Printer>::objectCount;
using Counted<Printer>::TooManyObjects;
private:
Printer();
Printer(const Printer& rhs);
}

方法一: 它用基类的两个成员,用静态成员,来避免了无法继承问题。(因为就是是私有,静态变量也能继承,毕竟同一块内存区)

也为后来的TooManyOBjects()和objectCount()函数调用做铺垫。

方法二:在头文件const只能初始化int size_t等类型

方法三:昨天一样,生成对象函数和复制函数用static,并返回。

方法四:私有继承也是继承,只要是继承,派生类就会拥有基类所有对象,只存在访问权限而已。
private权限导致派生类无法直接访问。
但是,派生类构造/析构函数默认是加入了基类的构造/析构函数的。Printer的调用,必定会导致Counted的调用,init便存在间接访问权限。

所以Printer可以只管用,计数功能完全基类代替。

不得不感叹作者写的太好了!

// //