C++ 学生类转换为教师类:保留共有数据成员
#include
class Person { protected: int num; string name; char sex;
public: Person(int n, string nam, char s) : num(n), name(nam), sex(s) {} void display() { cout << "num: " << num << endl; cout << "name: " << name << endl; cout << "sex: " << sex << endl; } };
class Student : public Person { private: int age; string major;
public: Student(int n, string nam, char s, int a, string m) : Person(n, nam, s), age(a), major(m) {} void display() { Person::display(); cout << "age: " << age << endl; cout << "major: " << major << endl; } };
class Teacher : public Person { private: string title;
public: Teacher(Student& stu) : Person(stu.num, stu.name, stu.sex), title("Teacher") {} void display() { Person::display(); cout << "title: " << title << endl; } };
int main() { Student stu(1001, "Tom", 'M', 20, "Computer Science"); Teacher tea(stu); tea.display(); return 0; }
原文地址: https://www.cveoy.top/t/topic/nVaw 著作权归作者所有。请勿转载和采集!