以下是相应的代码实现:

#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函数输出信息。需要注意的是,派生类的构造函数需要先调用基类的构造函数来初始化继承来的数据成员。

C++ 类继承示例:学生类 (Student) 继承人 (Person) 类

原文地址: https://www.cveoy.top/t/topic/ocqe 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录