C++primer 15.5节练习

练习15.18

只有当派生类公有继承基类时,用户代码才能使用派生类向基类的转换:B &tb=D;

Base *p=&d1; 正确,Pub_Derv是公有继承Base

p=&d2; 错误,Priv_Derv是私有继承Base

p=&d3; 错误,Prot_Dery是保护继承Base

p=&dd1; 正确,Derived_from_Public是公有继承于Pub_Dery的

p=&dd2; 错误,Priv_Derv是私有继承于Base

p=&dd3; 错误,Prot_Dery是保护继承于Base

练习15.19

 1 class Base  
 2 {  
 3     char priv;  
 4 protected:  
 5     int prot;  
 6 public:  
 7     void pub() {}  
 8     void memfcn(Base &b) { b = *this; } //正确  
 9 };  
10 struct Pub_Dery :public Base  
11 {  
12     void memfcn(Base &b) { b = *this; } //正确  
13     int f() { return prot; }  
14 };  
15 struct Prot_Dery :protected Base  
16 {  
17     void memfcn(Base &b) { b = *this; } //正确  
18 };  
19 struct Priv_Dery:private Base  
20 {  
21     void memfcn(Base &b) { b = *this; } //正确  
22     int f1() { return prot; }  
23 };  
24 struct dfpub :public Pub_Dery  
25 {  
26     void memfcn(Base &b) { b = *this; } //正确,公有继承派生类的派生类可以访问其公有与保护部分  
27     int use_base() { return prot; }  
28 };  
29 struct dfpro:public Prot_Dery  
30 {  
31     void memfcn(Base &b) { b = *this; } //正确,保护继承派生类的派生类可以访问其保护部分  
32 };  
33 struct dfpri :public Priv_Dery  
34 {  
35     void memfcn(Base &b) { b = *this; } //错误,Base类型不可访问,不允许对不可访问的基类“base”进行转换。原因是Priv_Dery是私有继承Base的,所以对于dfpri来说,其Priv_Dery部分的base部分是私有的 

练习15.20

见上

练习15.21

 

posted @ 2017-09-16 20:18  五月份小姐  阅读(277)  评论(0编辑  收藏  举报