问题描述:(Person类、 Student类、 Employee类、 Faculty类和 Staff类)
设计一个名为 Person的类,它的两个派生类为 Student和 Employee,以及 Employee的两个派生类 Faculty和 Staff。
一个人( person)有一个名字、一个地址、一个电话号码和一个e-mail地址。
一个学生( student)有一个年级属性( freshman、 sophomore、 junior或 senior)。将年级属性值定义为常量。
一个雇员( employee)有一个办公地点、一个薪水和一个雇用日期。
定义一个名为 MyDate的类,它包含year、 month和day三个数据域。
一个教师( faculty)有一个办公时间和一个级别。
一个教工(staff)有一个职务。
在 Person类中定义一个常量函数 toString,并在每个类中覆盖 to String函数,用来输出类名和人名。
画出这些类的UML图,实现该类,并编写一个测试程序,它创建一个 Person、一个 Student、一个 Empoyee、一个 Faculty和一个Staff对象,并调用它们的 toString函数。
#include <iostream>
using namespace std;
class Person{
private:
string name;
string adress;
int number;
string mail;
public:
Person(string x1,string x2,int x3,string x4):name(x1),adress(x2),number(x3),mail(x4){};
void tostring()
{
cout<<name<<","<<adress<<","<<number<<","<<mail;
}
};
class Student:public Person{
private:
int fm;
public:
Student(string x1,string x2,int x3,string x4,int x5):Person(x1,x2,x3,x4){fm=x5;};
void tostring()
{
cout<<endl;
Person::tostring();
cout<<",年级:大"<<fm<<endl;
}
};
class Employee:public Person{
private:
string adress;
double salary;
int time;
public:
Employee(string x1,string x2,int x3,string x4,string x11,double x22,int x33):Person(x1,x2,x3,x4){adress=x11;salary=x22;time=x33;}
void tostring()
{
cout<<endl;
Person::tostring();
cout<<"地址为:"<<adress<<","<<"薪水:"<<salary<<","<<"天数:"<<time<<endl;
}
};
class Faculty:public Employee{
private:
int s,f;
string j;
public:
Faculty(string x1,string x2,int x3,string x4,string x11,double x22,int x33,int x44,int x55,string x66):Employee(x1,x2,x3,x4,x11,x22,x33){s=x44;f=x55;j=x66;}
void tostring() //这里要注意一个问题就是间接派生类要初始化,就要用到参数列表初始化,然后自己类中的成员变量就要在里面进行初始化就可以了
{
Employee::tostring();
cout<<"时间:"<<s<<"时"<<f<<"分"<<","<<"级别:"<<j<<endl;
}
};
class Staff:public Employee{
private:
string zhiwu;
public:
Staff(string x1,string x2,int x3,string x4,string x11,double x22,int x33,string x44):Employee(x1,x2,x3,x4,x11,x22,x33){zhiwu=x44;}
void tostring()
{
Employee::tostring();
cout<<"职务:"<<zhiwu<<endl;
}
};
int main()
{
Person person("肖1","抗的路",36412,"qq.com");
person.tostring();
Student student("肖1","抗的路",36412,"qq.com",3);
student.tostring();
Employee employee("肖1","抗的路",36412,"qq.com","德芙喽",6660,10);
Faculty faculty("肖1","抗的路",36412,"qq.com","德芙喽",6660,10,3,35,"教授");
faculty.tostring();
Staff staff("肖1","抗的路",36412,"qq.com","德芙喽",6660,10,"后勤");
staff.tostring();
return 0; //注意几个问题就是实参类型一定要与形参类型一致;很容易就会搞错的!!!!!
}
需要注意的点:
1,需要注意的就是派生类的构造函数对基类的初始初始化的形式,注意,这里要用到 形参列表 具体细节在上面代码中给出;
2,就是主函数中的实参一定要与所调用的函数中的形参匹配。
3特别注意间接派生类的构造函数的初始化的问题.