C++ 类与继承实例:实现老师、学生和研究生类的关系
#include
class Teacher { public: string name; int age;
Teacher(string n, int a) {
name = n;
age = a;
}
void teach() {
cout << 'I am a teacher. My name is ' << name << '. I am ' << age << ' years old. My responsibility is teaching.' << endl;
}
};
class Student { public: string name; string studentID;
Student(string n, string id) {
name = n;
studentID = id;
}
void study() {
cout << 'I am a student. My name is ' << name << '. My student ID is ' << studentID << '. My responsibility is studying.' << endl;
}
};
class Graduate : public Teacher, public Student { public: Graduate(string n, int a, string id) : Teacher(n, a), Student(n, id) {}
void teach() {
cout << 'I am a graduate. My name is ' << name << '. I am ' << age << ' years old. My responsibility is teaching.' << endl;
}
void study() {
cout << 'I am a graduate. My name is ' << name << '. My student ID is ' << studentID << '. My responsibility is studying.' << endl;
}
};
int main() { Teacher teacher('John', 40); Student student('Alice', '123456'); Graduate graduate('Bob', 25, '789012');
teacher.teach();
student.study();
graduate.teach();
graduate.study();
return 0;
}
原文地址: https://www.cveoy.top/t/topic/f31D 著作权归作者所有。请勿转载和采集!