1.定义3个类: class Date、class Person 、class Student (1)class Date 数据:年、月、日 (protected) 接口:构造函数、输出函数 (public) (2)class Person 数据:姓名、出生日期、年龄、性别 (protected) 接口:构造函数、输出函数(所有数据)(public) (3)class Student 公有继承 Person类 数据:姓名、出生日期、年龄、性别、学号、专业 (protected) 接口:构造函数、输出函数(所有数据)(public) 2.主函数设计要求: 定义一个Student类的静态数组,长度为10 输入3个学生的信息 按行打印3个学生的信息
时间: 2024-02-18 08:04:52 浏览: 64
以下是代码实现:
```cpp
#include <iostream>
#include <string>
using namespace std;
class Date {
protected:
int year, month, day;
public:
Date(int y, int m, int d) : year(y), month(m), day(d) {}
void print() {
cout << year << "-" << month << "-" << day << endl;
}
};
class Person {
protected:
string name;
Date birthdate;
int age;
char gender;
public:
Person(string n, int y, int m, int d, char g) : name(n), birthdate(y, m, d), gender(g) {
// 计算年龄
int now_year = 2021;
age = now_year - y;
if (m > 9 || (m == 9 && d > 24)) {
age++;
}
}
void print() {
cout << "姓名:" << name << endl;
cout << "出生日期:";
birthdate.print();
cout << "年龄:" << age << endl;
cout << "性别:" << gender << endl;
}
};
class Student : public Person {
protected:
string id;
string major;
public:
Student(string n, int y, int m, int d, char g, string i, string mj)
: Person(n, y, m, d, g), id(i), major(mj) {}
void print() {
Person::print();
cout << "学号:" << id << endl;
cout << "专业:" << major << endl;
}
};
int main() {
Student stu_list[10];
for (int i = 0; i < 3; i++) {
string n, i, mj;
int y, m, d;
char g;
cout << "请输入第" << i+1 << "个学生的信息:" << endl;
cout << "姓名:";
cin >> n;
cout << "出生日期(年 月 日):";
cin >> y >> m >> d;
cout << "性别(M/F):";
cin >> g;
cout << "学号:";
cin >> i;
cout << "专业:";
cin >> mj;
stu_list[i] = Student(n, y, m, d, g, i, mj);
}
cout << "所有学生的信息如下:" << endl;
for (int i = 0; i < 3; i++) {
stu_list[i].print();
}
return 0;
}
```
注:以上代码中的年龄计算方式并不严谨,只是为了演示方便。
阅读全文