继承
继承(Inheritance)是面向对象程序设计中实现代码复用的核心手段。它允许我们在保持基类特性的基础上进行扩展,增加新的成员函数和属性,从而生成派生类。
1. 继承的概念
假设我们有两个类 Student 和 Teacher,它们都包含姓名、地址、年龄、电话等公共成员,以及身份认证功能。如果分别定义,代码会非常冗余。
class Student {
public:
// 进入校园/图书馆刷二维码等身份认证
void identity() {
// ...
}
// 学习
void study() {
// ...
}
protected:
string _name = "peter";
string _address;
string _tel;
int _age = 18;
int _stuid;
};
class Teacher {
public:
void identity() {
// ...
}
// 授课
void teaching() {
// ...
}
protected:
string _name = "张三";
int _age = 18;
string _address;
string _tel;
string _title;
};
int main() {
return 0;
}
我们可以将公共成员提取到 Person 类中,让 Student 和 Teacher 继承 Person,这样就能复用这些成员,避免重复定义。
std;
{
:
{
cout << << _name << endl;
}
:
string _name = ;
string _address;
string _tel;
_age = ;
};
: Person {
:
{
}
:
_stuid;
};
: Person {
:
{
}
:
string title;
};
{
Student s;
Teacher t;
s.();
t.();
;
}




