C++,看简介,设计一个人员类和一个日期类有人员类派生学生类和教师类学生类和教师类的数据成员为日期类

2025-04-29 10:17:36
推荐回答(1个)
回答1:

代码如下:

#include 
#include 

using namespace std;

class person 
{
public:
person(const string& name)
: name(name) {}

const string& getName() const {
return name;
}
private:
string name;
};

class date {

public:
date(int year, int month, int day)
:year(year), month(month), day(day)
{}

int getYear() const {
return year;
}
int getMonth() const {
return month;
}
int getDay() const {
return day;
}

friend ostream& operator << (ostream& out, const date& date) {
out << date.year << "-" << date.month << "-" << date.day;
return out;
}

private:
int year;
int month;
int day;
};

class student : public person
{
public:
student(const string& name, date birthday)
: person(name), birthday(birthday) {}

const date& getBirthday() const {
return birthday;
}
private:
date birthday;
};

class professor : public person
{
public:
professor(const string& name, date birthday)
: person(name), birthday(birthday) {}

const date& getBirthday() const {
return birthday;
}
private:
date birthday;
};

int main()
{
student stu1("张三", date(1988, 5, 4));
cout << "类型:学生" << ",姓名:" << stu1.getName() << ",生日:" << stu1.getBirthday() << endl;

professor pro1("王五", date(1970, 10, 5));
cout << "类型:教师" << ",姓名:" << pro1.getName() << ",生日:" << pro1.getBirthday() << endl;

system("pause");
return 0;
}

运行结果: