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

关于#c++#的问题:采取公用继承方式写出Person类的派生类:Student,有数据成员:分数,在Student类中包括一个输出函数
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
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; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报