题目要求
定义一个 Teacher(教师)类和一个 Student(学生)类,二者有一部分数据成员是相同的,例如 num, name, sex 。编写程序,将一个 Student 对象(学生)转换为Teacher(教师)类,只将以上3个相同的数据成员移植过去。可以设想为:一个学生大学毕业了,留校担任教师,他原有的部分数据对现在的教师身份来说仍然是有用的,应当保留并成为其教师的数据的一部分。
——谭浩强的《C++面向对象程序设计》第4章习题第7小题
程序
/* ************************************************************************* @file: main.cpp @date: 2020.12.5 @author: Xiaoxiao @brief: 学生留校担任老师 @blog: https://blog.csdn.net/weixin_43470383/article/details/110679348 ************************************************************************* */ #define _CRT_SECURE_NO_WARNINGS // VS中屏蔽函数strcpy()的错误,注意必须放首行! #include <iostream> using namespace std; class Student { public: Student(int n, char nam[], char s, float sc) ; // 实现初始化的构造函数 int get_num() { return num; } char * get_name() { return name; } char get_sex() { return sex; } void display(); private: int num; char name[10]; char sex; float score; }; Student::Student(int n, char nam[], char s,float sc) { num = n; strcpy(name, nam); sex = s; score = sc; } void Student::display() { cout << "num:" << num << "\nname:" << name << "\nsex:" << sex << "\nscore:" << score << "\n\n"; } class Teacher { public: Teacher() {}; // 默认构造函数 Teacher(Student&); // 转换构造函数 Teacher(int n, char nam[], char s, float w); // 实现初始化的构造函数 void display(); private: int num; char name[20]; char sex; float wage; }; Teacher::Teacher(int n, char nam[], char s, float w) { num = n; strcpy(name, nam); sex = s; wage = w; } Teacher::Teacher(Student& stud) { num = stud.get_num(); strcpy(name, stud.get_name()); sex = stud.get_sex(); wage = 10000; } void Teacher::display() { cout << "num:" << num << "\nname:" << name << "\nsex:" << sex << "\nwage:" << wage << "\n\n"; } int main() { Teacher teacher1(30001226, "Zhou", 'm', 12000.0), teacher2; Student student1(21030208, "Xiaoxiao", 'f', 100.0); cout << "student1:" << endl; student1.display(); teacher2 = Teacher(student1); // 将 student1 转为 Teacher 类型 cout << "teacher2:" << endl; teacher2.display(); system("pause"); return 0; }
运行结果
输出:
student1:
num:21030208
name:Xiaoxiao
sex:f
score:100
teacher2:
num:21030208
name:Xiaoxiao
sex:f
wage:10000