/* *Copyright(C) 2016,计算机与控制工程学院 *All rights reserved. *文件名:test.cpp *作者:张志新 *完成日期:2016年5月1日 *版本号:v1.0 * *问题描述:分别定义Teacher(教师)类和Cadre(干部)类,采用多重继承方式由这两个类派生出新类Teacher_Cadre(教师兼干部). */ #include<iostream> using namespace std; class Teacher { protected: int age; string name; char sex; string address; int number; string title;//职称 public: void display(); Teacher(string n,int a,char s,string addr,int num,string t); }; Teacher::Teacher(string n,int a,char s,string addr,int num,string t): age(a),name(n),sex(s),address(addr),number(num),title(t){} void Teacher::display() { cout<<"name:"<<name<<endl; cout<<"age:"<<age<<endl; cout<<"sex:"<<sex<<endl; cout<<"title:"<<title<<endl; cout<<"address:"<<address<<endl; cout<<"tel:"<<number<<endl; } class Cadre { protected: int age; string name; char sex; string address; int number; string post;//职务 public: Cadre(string n,int a,char s,string addr,int num,string p); void display(); }; Cadre::Cadre(string n,int a,char s,string addr,int num,string p): age(a),name(n),sex(s),address(addr),number(num),post(p){} void Cadre::display() { cout<<"name:"<<name<<endl; cout<<"age:"<<age<<endl; cout<<"sex:"<<sex<<endl; cout<<"post:"<<post<<endl; cout<<"address:"<<address<<endl; cout<<"tel:"<<number<<endl; } class Teacher_Cadre:public Teacher,public Cadre { private: int age; string name; char sex; string address; int number; double wages;//工资 public: void show(); Teacher_Cadre(string n,int a,char s,string addr,int num,string p,string t,double w); }; Teacher_Cadre::Teacher_Cadre(string n,int a,char s,string addr,int num,string p,string t,double w): Teacher(n,a,s,addr,num,p),Cadre(n,a,s,addr,num,t),wages(w){} void Teacher_Cadre::show() { Teacher::display(); cout<<"post:"<<Cadre::post<<endl; cout<<"wages:"<<wages<<endl; } int main() { Teacher_Cadre t1("cindy",20,'F',"jinan",12345678,"jiangshi","shouke",40000); t1.show(); return 0; }
学习心得:
这个程序运用的知识点是多重继承,在派生类写基类名时两个基类要用“,”而不是“:”,在传入一个char型字符时要用单引号,在传入string的字符串时用双引号。在派生类中调用基类中重名的成员函数时,其中一个类中的成员函数是要Teacher::display()这种形式否者会出先编译错误。在调运基类中的数据成员时要这种形式Cadre::post否则编译错误。