#include #include using namespace std;

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

BirthDate::BirthDate(int y, int m, int d) //给出BirthDate类的构造函数的实现 { 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 n = 0, char na[] = "", char s = ' '); //声明构造函数 void display(); //声明输出函数 private: int num; char name[20]; char sex; };

Teacher::Teacher(int n, char na[], char s) //给出Teacher类的构造函数的实现 { num = n; strcpy(name, na); sex = s; }

void Teacher::display() //输出函数的实现 { cout << "num:" << num << endl; cout << "name:" << name << endl; cout << "sex:" << sex << endl; }

class Professor: public Teacher //教授类继承自教师类 { public: Professor(int n = 0, char na[] = "", char s = ' ', int y = 0, int m = 0, int d = 0, double a = 0.0); //声明构造函数 void display(); //声明输出函数 void change(int y, int m, int d, double a); //声明修改函数 private: BirthDate birthday; //生日类对象 double area; };

Professor::Professor(int n, char na[], char s, int y, int m, int d, double a): Teacher(n, na, s), birthday(y, m, d) { area = a; }

void Professor::display() //定义输出函数 { Teacher::display(); birthday.display(); cout << "area:" << area << endl; }

void Professor::change(int y, int m, int d, double a) //定义修改函数 { birthday.change(y, m, d); area = a; }

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, 130.5);
prof1.display();
return 0; }

运行结果截图如下:

image.png

C++ 教师类、生日类和教授类:面向对象编程示例

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

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