m0_73838507 2023-04-05 19:14 采纳率: 85.7%
浏览 22
已结题

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

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

  • 写回答

2条回答 默认 最新

  • threenewbee 2023-04-05 21:12
    关注

    第一问的代码

    #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;
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 4月14日
  • 已采纳回答 4月6日
  • 创建了问题 4月5日

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值