1、建立Person类作为所有派生类的基类,数据成员包含一个字符串name、year、month、day四个数据成员,在类中设计一个虚函数Print,打印所有数据成员信息。 2、由Person类派生一个Teacher类,增加工号Tno字符串成员。 3、由Person类派生一个Student类,增加学号Sno字符串成员。 4、在Teacher设计虚函数Print输出教师工号,在Student类中设计虚函数Print输出学生学号。 5、在主函数中利用基类指针指向派生类,结合虚函数实现多态。
时间: 2024-03-20 16:39:10 浏览: 34
好的,根据您的要求,我来为您编写代码:
```c++
#include <iostream>
#include <string>
using namespace std;
// 定义Person类作为基类
class Person {
protected:
string name; // 姓名
int year; // 出生年份
int month; // 出生月份
int day; // 出生日期
public:
Person(string n, int y, int m, int d) : name(n), year(y), month(m), day(d) {}
virtual void Print() {
cout << "姓名:" << name << endl;
cout << "出生日期:" << year << "年" << month << "月" << day << "日" << endl;
}
};
// 定义Teacher类,继承自Person类
class Teacher : public Person {
private:
string Tno; // 工号
public:
Teacher(string n, int y, int m, int d, string t) : Person(n, y, m, d), Tno(t) {}
virtual void Print() {
Person::Print(); // 调用基类的Print函数,打印姓名和出生日期
cout << "工号:" << Tno << endl;
}
};
// 定义Student类,继承自Person类
class Student : public Person {
private:
string Sno; // 学号
public:
Student(string n, int y, int m, int d, string s) : Person(n, y, m, d), Sno(s) {}
virtual void Print() {
Person::Print(); // 调用基类的Print函数,打印姓名和出生日期
cout << "学号:" << Sno << endl;
}
};
int main() {
// 定义基类指针和派生类对象
Person* ptr;
Teacher t("张三", 1980, 3, 14, "1001");
Student s("李四", 2000, 9, 1, "20180101");
// 通过基类指针指向派生类对象,实现多态
ptr = &t;
ptr->Print(); // 调用Teacher类的Print函数
cout << endl;
ptr = &s;
ptr->Print(); // 调用Student类的Print函数
cout << endl;
return 0;
}
```
希望这段代码能够满足您的要求,如果有任何问题,欢迎继续提问!
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)