有一个类Date包含int year int month int day三个protected数据。有一个基类Person包含string namechar sexint age三个protected数据 和 一个print函数用于输出数据信息。有一个Person的派生类Student新增int ID 、Date birthday、Person mother三个数据成员。要求每个类写好 含参
以下是相应的代码实现:
#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) {}
};
class Person {
protected:
string name;
char sex;
int age;
public:
Person(string n, char s, int a) : name(n), sex(s), age(a) {}
void print() { cout << "Name: " << name << ", Sex: " << sex << ", Age: " << age << endl; }
};
class Student : public Person {
private:
int ID;
Date birthday;
Person mother;
public:
Student(string n, char s, int a, int id, Date bd, Person m) : Person(n, s, a), ID(id), birthday(bd), mother(m) {}
};
int main() {
Date bd(1998, 8, 12);
Person m("Mary", 'F', 50);
Student st("Tom", 'M', 20, 123456, bd, m);
st.print();
return 0;
}
在主函数中,先创建了一个Date对象bd和一个Person对象m,然后通过这两个对象创建了一个Student对象st。最后调用st的print函数输出信息。需要注意的是,派生类的构造函数需要先调用基类的构造函数来初始化继承来的数据成员
原文地址: https://www.cveoy.top/t/topic/flTy 著作权归作者所有。请勿转载和采集!