继承概述
继承(Inheritance)是 C++ 面向对象程序设计实现代码复用的最重要手段。它允许我们在保持原有类特性的基础上进行扩展,增加新的方法(成员函数)和属性(成员变量),从而产生新的类,称为派生类。
为什么需要继承?
想象一下,如果我们要定义 Student 和 Teacher 两个类。这两个类里面都有姓名、地址、年龄、电话等成员变量,都有身份认证的成员函数。如果不使用继承,设计时就会出现大量冗余。
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
// 进入校园/图书馆/实验室刷二维码等身份认证
void identity() {
cout << "Student Identity" << endl;
}
// 学习
void study() {
// ...
}
protected:
string _name = "peter"; // 姓名
string _address; // 地址
string _tel; // 电话
int _age = 18; // 年龄
int _stuid; // 学号
};
class Teacher {
public:
void identity() {
cout << "Teacher Identity" << endl;
}
// 授课
void teaching() {
}
:
string _name = ;
_age = ;
string _address;
string _tel;
string _title;
};
{
;
}





