用c++语言编写设计人员类Person和日期类date,人员类派生出学生类Student和教师类Teacher。教师类包含姓名、生日、ID、专业、所属机构,学生类包含姓名、ID、成绩、生日,教师类与学生类的数据成员birthday(生日)为日期类的对象
时间: 2023-10-20 17:26:16 浏览: 32
可以参考如下代码实现:
```cpp
#include <iostream>
#include <string>
using namespace std;
// 日期类
class Date {
public:
Date(int year, int month, int day) : year_(year), month_(month), day_(day) {}
int year() const { return year_; }
int month() const { return month_; }
int day() const { return day_; }
private:
int year_;
int month_;
int day_;
};
// 人员类
class Person {
public:
Person(const string& name, const Date& birthday) : name_(name), birthday_(birthday) {}
string name() const { return name_; }
Date birthday() const { return birthday_; }
private:
string name_;
Date birthday_;
};
// 学生类
class Student : public Person {
public:
Student(const string& name, int id, int score, const Date& birthday)
: Person(name, birthday), id_(id), score_(score) {}
int id() const { return id_; }
int score() const { return score_; }
private:
int id_;
int score_;
};
// 教师类
class Teacher : public Person {
public:
Teacher(const string& name, const Date& birthday, int id, const string& major, const string& institution)
: Person(name, birthday), id_(id), major_(major), institution_(institution) {}
int id() const { return id_; }
string major() const { return major_; }
string institution() const { return institution_; }
private:
int id_;
string major_;
string institution_;
};
int main() {
Date d1(1999, 1, 1);
Date d2(1970, 5, 5);
Student s("张三", 1, 90, d1);
Teacher t("李四", d2, 1001, "计算机科学", "清华大学");
cout << s.name() << " " << s.id() << " " << s.score() << " " << s.birthday().year() << "-" << s.birthday().month() << "-" << s.birthday().day() << endl;
cout << t.name() << " " << t.id() << " " << t.major() << " " << t.institution() << " " << t.birthday().year() << "-" << t.birthday().month() << "-" << t.birthday().day() << endl;
return 0;
}
```
这里与之前的代码不同,日期类 `Date` 的构造函数需要接收年、月、日三个参数,由于数据成员是私有的,因此需要提供公有的成员函数分别返回年、月、日。
人员类 `Person` 的构造函数也需要接收一个 `Date` 对象作为生日,由于生日是一个私有成员变量,因此需要提供公有的成员函数返回生日。
学生类 `Student` 和教师类 `Teacher` 的构造函数都需要调用父类 `Person` 的构造函数来初始化姓名和生日,因此在参数列表中需要传入这些参数。另外,由于学生类和教师类都有生日这个数据成员,因此在 `Person` 类中需要提供一个公有的成员函数返回生日。
在 `main` 函数中创建两个日期对象 `d1` 和 `d2`,然后分别创建一个学生对象 `s` 和一个教师对象 `t`,并调用它们的成员函数输出各自的信息。