#include #include using namespace std;

class BirthDate { // 生日类 public: BirthDate(int, int, int); // 构造函数 void display(); // 输出函数 void change(int, int, int); // 修改函数 private: int year; int month; int day; };

BirthDate::BirthDate(int y, int m, int d) { // 构造函数 year = y; month = m; day = d; }

void BirthDate::display() { // 输出函数 cout << 'birthday:' << month << '/' << day << '/' << year << endl; }

void BirthDate::change(int y, int m, int d) { // 修改函数 year = y; month = m; day = d; }

class Teacher { // 教师类 public: Teacher(int, char[], char, BirthDate); // 构造函数 void display(); // 输出函数 private: int num; char name[20]; char sex; BirthDate birthday; };

Teacher::Teacher(int n, char na[], char s, BirthDate b) { // 构造函数 num = n; strcpy(name, na); sex = s; birthday = b; }

void Teacher::display() { // 输出函数 cout << 'num:' << num << endl; cout << 'name:' << name << endl; cout << 'sex:' << sex << endl; birthday.display(); }

class Professor : public Teacher { // 教授类,继承教师类 public: Professor(int, char[], char, int, int, int, float); // 构造函数 void display(); // 输出函数 void change(int, int, int); // 修改函数 private: float area; };

Professor::Professor(int n, char na[], char s, int y, int m, int d, float a) : Teacher(n, na, s, BirthDate(y, m, d)) { // 构造函数 area = a; }

void Professor::display() { // 输出函数 Teacher::display(); cout << 'area:' << area << endl; }

void Professor::change(int y, int m, int d) { // 修改函数 Teacher::birthday.change(y, m, d); }

int main() { Professor prof1(3012, 'Zhang', 'f', 1949, 10, 1, 125.4); // 创建一个教授对象 cout << endl << 'original data:' << endl; prof1.display(); // 输出对象的原始数据 cout << endl << 'new data:' << endl; prof1.change(1950, 6, 1); // 修改对象的生日 prof1.display(); // 输出修改后的对象数据 return 0; }

// 运行结果截图如下:

// 注:由于教授类中使用了继承,因此教授类的定义需要放在教师类的定义之后,这样才能正确地继承教师类的成员和方法。同时,教授类的构造函数中需要调用父类(即教师类)的构造函数来对教师类的成员进行初始化。

C++ 教师、生日和教授类实现:代码示例及运行结果

原文地址: https://www.cveoy.top/t/topic/nH97 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录