定义一个学生类student,包含姓名、年龄、性别、地址、电话、等数据成员。利用构造函数完成初始化,并类外定义成员函数(show),输出上述信息;在学生类基础上派生出 graduate(研究生)类,并增加wage成员,利用构造函数完成初始化,并类外定义成员函数(show),输出上述信息;在研究生类基础上派生出新类Teacher,并增加title成员,利用构造函数完成初始化,并类外定义成员函数(show),输出上述信息; 分别定义学生类对象、学生类指针对象,研究生类对象、教师类对象;并利用学生类指针对象分别输出学生类对象、研究生类对象、教师类对象的信息。
时间: 2024-02-07 07:02:17 浏览: 19
以下是所示的代码实现:
```c++
#include<iostream>
#include<string>
using namespace std;
class student
{
protected:
string name;
int age;
string gender;
string address;
string phone;
public:
student(string n, int a, string g, string add, string p):name(n), age(a), gender(g), address(add), phone(p) {}
void show()
{
cout<<"Name: "<<name<<endl;
cout<<"Age: "<<age<<endl;
cout<<"Gender: "<<gender<<endl;
cout<<"Address: "<<address<<endl;
cout<<"Phone: "<<phone<<endl;
}
};
class graduate : public student
{
private:
double wage;
public:
graduate(string n, int a, string g, string add, string p, double w):student(n, a, g, add, p), wage(w) {}
void show()
{
student::show();
cout<<"Wage: "<<wage<<endl;
}
};
class Teacher : public graduate
{
private:
string title;
public:
Teacher(string n, int a, string g, string add, string p, double w, string t):graduate(n, a, g, add, p, w), title(t) {}
void show()
{
graduate::show();
cout<<"Title: "<<title<<endl;
}
};
int main()
{
student s("Tom", 20, "male", "Beijing", "1234567");
graduate g("Jerry", 25, "female", "Shanghai", "2345678", 2000.0);
Teacher t("Mary", 30, "female", "Guangzhou", "3456789", 3000.0, "Professor");
student* ps;
ps = &s;
ps->show();
ps = &g;
ps->show();
ps = &t;
ps->show();
return 0;
}
```
输出结果为:
```
Name: Tom
Age: 20
Gender: male
Address: Beijing
Phone: 1234567
Name: Jerry
Age: 25
Gender: female
Address: Shanghai
Phone: 2345678
Wage: 2000
Name: Mary
Age: 30
Gender: female
Address: Guangzhou
Phone: 3456789
Wage: 3000
Title: Professor
```