关于#c++#的问题:采取公用继承方式写出Person类的派生类:Student,有数据成员:分数,在Student类中包括一个输出函数

设计Person类,有姓名,年龄,其数据成员的访问属性为private,并包括一个信息输出函数display()。采取公用继承方式写出Person类的派生类:Student,有数据成员:分数,在Student类中包括一个输出函数。在main()函数中分别实现两类对象信息输出。
1)将Person类和Student类的信息输出函数,名称统一,完善程序。
2)将Person类数据成员的访问属性改为protected,采取公用继承方式写出Student类,并完善程序。

第一问的代码

#include <iostream>
#include <string>

class Person {
protected:  // 姓名和年龄访问属性改为 protected
    std::string name;
    int age;
public:
    Person(const std::string& name, int age) : name(name), age(age) {}
    void display() const {
        std::cout << "Name: " << name << "\nAge: " << age << std::endl;
    }
};

class Student : public Person {
private:
    double score;
public:
    Student(const std::string& name, int age, double score) : Person(name, age), score(score) {}
    void display() const {
        Person::display();  // 调用基类的 display() 函数
        std::cout << "Score: " << score << std::endl;
    }
};

int main() {
    Person p("Tom", 20);
    p.display();  // 输出姓名和年龄

    Student s("Jerry", 18, 90.5);
    s.display();  // 输出姓名、年龄和分数

    return 0;
}

下面是将 Person 类数据成员的访问属性改为 protected

#include <iostream>
#include <string>

class Person {
protected:  // 姓名和年龄访问属性改为 protected
    std::string name;
    int age;
public:
    Person(const std::string& name, int age) : name(name), age(age) {}
    void display() const {
        std::cout << "Name: " << name << "\nAge: " << age << std::endl;
    }
};

class Student : public Person {
private:
    double score;
public:
    Student(const std::string& name, int age, double score) : Person(name, age), score(score) {}
    void display() const {
        Person::display();  // 调用基类的 display() 函数
        std::cout << "Score: " << score << std::endl;
    }
};

int main() {
    Person p("Tom", 20);
    p.display();  // 输出姓名和年龄

    Student s("Jerry", 18, 90.5);
    s.display();  // 输出姓名、年龄和分数

    Person* p1 = new Student("Bob", 22, 85.5);  // 基类指针指向派生类对象
    p1->display();  // 调用基类的 display() 函数输出姓名和年龄

    delete p1;

    return 0;
}

不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^