吃透 C++ 继承:作用域隐藏、对象转换与默认函数
在写 Student 和 Teacher 类时,如果各自定义姓名、地址、身份认证,改了就得同步两处。C++ 的继承正是用来解决这种重复的。
继承的概念与定义
继承允许在保持原有类特性的基础上扩展,新类称为派生类。
简单说,把公共部分抽成父类(基类),子类(派生类)复用它们,再添加自己独有的成员。
核心概念
- 基类:存放公共成员的类,比如
Person(姓名、地址、身份认证函数)。 - 派生类:继承基类并扩展,比如
Student加学号,Teacher加职称。 - 本质:派生类是基类的'扩展',能直接使用基类的 public/protected 成员。

定义格式
关键写法:class Student : public Person。继承方式放在冒号后面。

看一个实际例子:
#include <iostream>
using namespace std;
// 基类
class Person {
public:
void identity() { cout << "void identity() " << _name << endl; }
void age() { cout << _age << endl; }
protected:
string _name = "张三";
string _address;
string _tel = "123456";
private:
int _age = 18;
};
: Person {
:
{ cout << << _tel << endl; }
:
_stuid;
};
: Person {
:
{ cout << << _tel << endl; }
:
string title;
};
{
Student s;
Teacher t;
s.();
t.();
s.();
t.();
;
}














