练习15.18:
Base* p = &d1:合法
p = &d2:不合法,只有当派生类公有地继承基类时,用户代码才能使用派生类向基类的转换
p = &d3:不合法,只有当派生类公有地继承基类时,用户代码才能使用派生类向基类的转换
p = &dd1:合法
p = &dd2:不合法,只有当派生类公有地继承基类时,用户代码才能使用派生类向基类的转换
p = &dd3:不合法,只有当派生类公有地继承基类时,用户代码才能使用派生类向基类的转换
练习15.19:
对于类Base:合法
对于类Pub_Derv:合法
对于类Prot_Derv:合法
对于类Priv_Derv:合法
对于类Derived_from_Public:合法
对于类Derived_from_Protected:合法
对于类Derived_from_Private:不合法,因为类Derived_from_Private的直接基类Priv_Derv自Base私有继承而来,所以Derived_from_Private的成员无法使用Priv_Derv向Base,也就无法实现Derived_from_Private到Base的转换
练习15.20:
#include <iostream>
#include <string>
#include <errno.h>
using namespace std;
class Base {
public:
void pub_mem();
//正确
void memfcn(Base& b) { b = *this; cout << "Base memfcn success" << endl; }
protected:
int prot_mem;
private:
char priv_mem;
};
struct Pub_Derv :public Base {
int f() { return prot_mem; }
//错误
//char g() { return priv_mem; }
//正确
void memfcn(Base& b) { b = *this; cout << "Pub_Derv memfcn success" << endl;}
};
struct Priv_Derv :private Base {
int f1()const { return prot_mem; }
//正确
void memfcn(Base& b) { b = *this; cout << "Priv_Derv memfcn success" << endl;}
};
struct Prot_Derv :protected Base {
int f1()const { return prot_mem; }
//正确
void memfcn(Base& b) { b = *this; cout << " Prot_Derv memfcn success" << endl;}
};
struct Derived_from_Public :public Pub_Derv {
int use_base() { return prot_mem; }
//正确
void memfcn(Base& b) { b = *this; cout << "Derived_from_Public memfcn success" << endl;}
};
struct Derived_from_Protected :public Prot_Derv {
int use_base() { return prot_mem; }
//正确
void memfcn(Base& b) { b = *this; cout << "Derived_from_Protected memfcn success" << endl;}
};
struct Derived_from_Private :public Priv_Derv {
//错误
//int use_base() { return prot_mem; }
//不正确
//void memfcn(Base& b) { b = *this; }
};
//测试
int main()
{
Base b1, b2;
Pub_Derv d1;
Priv_Derv d2;
Prot_Derv d3;
Derived_from_Public dd1;
Derived_from_Private dd2;
Derived_from_Protected dd3;
Base* p = &d1;
//p = &d2;
//p = &d3;
p = &dd1;
//p = &dd2;
//p = &dd3;
b1.memfcn(b2);
d1.memfcn(b2);
d2.memfcn(b2);
d3.memfcn(b2);
dd1.memfcn(b2);
dd3.memfcn(b2);
system("pause");
return 0;
}
结果:
练习15.21:
对于(b) 图形基元中的类型组成继承体系:
首先是所有图形的基类Figure,接下来是其派生类圆形类Circular,方形Square,椭圆形Oval、圆锥,球等等。。。
练习15.22:
公共成员:获得长、宽高的函数或者获得长,宽,高的函数
受保护成员:各种图形的长宽高
虚函数:计算图形面积、体积