1. 继承的概念
继承(Inheritance)是面向对象程序设计中实现代码复用的核心机制。它允许在保持原有类特性的基础上进行扩展,增加新的成员函数和成员变量,由此产生的新类称为派生类(Derived Class),原有类称为基类(Base Class)。
若不采用继承机制,设计具有相似属性的类时会导致代码冗余。例如 Student 和 Teacher 类都包含姓名、地址、年龄、电话等成员变量,以及身份认证函数 identity():
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;
};
通过引入公共基类 Person,让 Student 和 Teacher 继承 Person,即可复用公共成员,消除冗余:
class Person {
public:
void identity { cout << << _name << endl; }
:
string _name = ;
string _address;
string _tel;
_age = ;
};
: Person {
:
{ }
:
_stuid;
};
: Person {
:
{ }
:
string title;
};
{
Student s;
Teacher t;
s.();
t.();
;
}





