而且假定只关心这几类雇员各自的如下一些数据: employee(雇员)类: 姓名、年龄、工资; manager(经理)类: 姓名、年龄、工资、行政级别; engineer(工程师)类: 姓名、年龄、工资、专业、学位; director(高级主管)类:姓名、年龄、工资、行政级别、职务。
employee
manager engineer
director
4个类之间的继承关系
#include
class employee //employee类(类型),将作为其它几个类的基类 { short age; float salary; protected:
char * name; public: employee (short ag, float sa, char * na)
{ age=ag; salary=sa; name=new char[strlen(na)+1]; strcpy(name,na); } void print () const
{ cout<<\ \ cout< class manager:public employee //派生类manager { int level; public: manager(short ag, float sa, char* na, int lev) :employee (ag,sa,na) //对基类初始化负责 17 { level=lev; } void print()const { employee::print(); //调用基类print显示“共性”数据 cout <<\ } }; /*注意:允许派生类中的print与基类的print重名,按如下规定进行处理:对子类而言,不加类名限定时默认为是处理子类成员,而要访问父类重名成员时,则要通过类名限定*/ class engineer:public employee //派生类engineer { char speciality,adegree; /*专业:‘E’--电子,‘M’—机械,‘C’—计算机,‘A’—自动化专业; 学位:‘O’—博士 , ‘M’—硕士 , ‘B’—学士 , ‘N’—无学位 * / public: engineer (short ag , float sa , char * na ,char sp ,char ad): employee (ag,sa,na) {speciality=sp; //派生类的构造函数 adegree =ad; } void print()const { employee::print(); //调用基类print显示“共性”数据 cout <<\ speciality:\ cout <<\ academic degree:\ } }; enum ptitle {PS,GM,VPS,VGM}; class director:public manager //派生类director { ptitle post; public: director(short ag ,float sa ,char*na , int lev ,ptitle po): manager(ag,sa,na,lev) { post =po ; } //派生类的构造函数 void print()const { manager::print(); cout <<\ post:\ } }; void main() { //主函数 employee emp1(23,610.5,\ manager man1(32,812.45,\ engineer eng(26,1420.10,\ director dir(38,1800.2,\ emp1.print(); emp2.print(); 18 man1.print(); man2.employee::print(); //调用基类的print eng.print(); dir.print(); } 程序执行后的显示结果如下: zhang: 23 : 610.5 zhao: 27 : 824.75 li: 32 : 812.45 level:11 cui: 34 : 1200.5 meng: 26 : 1420.1 speciality:E academic degree:M zhou: 38 : 1800.2 level:2 post:1 例11 (program 8-2 p257) 分析下述程序中的继承与派生关系. #include class D11 : public B { public: void f11() { pubDat=11; //OK! 仍为public proDat=12; //OK! protected priDat=13; /ERROR! 基类的私有成员不可访问 } }; class D21 : public D11 { public: void f21() { pubDat=121; //OK! 仍为public proDat=122; //OK! 仍为protected 19 priDat=131; //ERROR! 基类的私有成员不可访问 } }; class D12 : protected B { public: void f12() { pubDat=21; //OK! 变为protected proDat=22; //OK! 仍为protected priDat=23; //ERROR! 基类的私有成员不可访问 } }; class D22 : public D12 { public: void f22() { pubDat=221; //OK! 仍为protected proDat=222; //OK! 仍为protected priDat=223; //ERROR! 基类的私有成员不可访问 } }; class D13: private B { public: void f13() { pubDat=31; //OK! 变为private 可以访问 proDat=32; //OK! 变为private 可以访问 priDat=33; //ERROR! 基类的私有成员不可访问 } }; class D23 : public D13 { public: void F23() { pubDat=311; //ERROR! 基类的私有成员不可访问 proDat=321; //ERROR! 基类的私有成员不可访问 priDat=331; //ERROR! 基类的私有成员不可访问 } }; void main() { B ob0; ob0.pubDat=1; //OK! 可以访问public成员 ob0.proDat=2; //ERROR! 不可以访问protected成员 20

