实验4 继承与派生-程序 下载本文

内容发布更新时间 : 2024/7/1 22:11:40星期一 下面是文章的全部内容请认真阅读。

实验4 继承与派生---参考程序

二、实验内容

1.定义一个基类有姓名、性别、年龄,再由基类派生出教师类和学生类,教师类增加工号、职称和工资,学生类增加学号、班级、专业和入学成绩。

#include #include using namespace std; class Person {

public: Person(string s1,int s2,string s3): name(s1),age(s2),gender(s3){} void show() { cout<

class Teacher: public Person {

public: Teacher(string s1,int s2,string s3,string s4,string s6):Person(s1,s2,s3),num(s4),title(s5),salary(s6){}

void show() {// Person::show(); cout<

class Student:public Person{ public: Student(string s1,int s2,string s3,string s4,string s5,string s6,double s7): Person(s1,s2,s3),num(s4),Class(s5),major(s6),score(s7){} void show() { Person::show(); cout<

s5,double string major; double score; };

int main(void) { Teacher T(\ Student S(\ cout<<\姓名\年龄\性别\工号\职称\薪水\

T.Person::show(); T.show(); cout<<\姓名\年龄\性别\学号\班级\专业\成绩\

S.show(); return 0; }

2.设计一个圆类Circle和一个桌子类Table,再由它们共同派生出圆桌类RoundTable,要求输出一个圆桌的高度、面积和颜色等数据。 #include #include using namespace std; class Circle {

public: Circle(double r):radius(r){} double area() {return 3.14159*radius*radius;} private: double radius; };

class Table {

public: Table(string c,double h):color(c),height(h){} void show() { cout<<\ private: string color; double height; };

class Roundtable: public Circle,public Table {

public:

Roundtable(double r,string c,double h):Circle(r),Table(c,h){} };

int main(void) { Roundtable R(4,\ R.show(); cout<<\ return 0; }

3. 分别定义教师类Teacher和干部类Cadre,采用多重继承的方式由这两个类派生出新类Teacher_Cadre(教师兼干部类)。要求:

#include #include using namespace std; class Teacher {public:

Teacher(string nam, int a, char s, string tit, string ad, string t); void display(); protected:

string name; //姓名 int age; //年龄 char sex; //性别 string title; //职称 string addr; //地址 string tel; //电话 };

Teacher::Teacher(string nam, int a, char s, string tit, string ad, string t): name(nam), age(a), sex(s), title(tit), addr(ad), tel(t){ }

void Teacher::display()

{ cout << \ cout << \ cout << \ cout << \ cout << \ cout << \}

class Cadre {public:

Cadre(string nam, int a, char s, string p, string ad, string t); void display(); protected:

string name; //姓名 int age; //年龄