前言
继承是面向对象编程的核心特性之一,它允许我们在保持原有类特性的基础上进行扩展,增加方法和属性,从而产生新的类。这体现了由简单到复杂的认知过程,也是代码复用的重要手段。
一、什么是继承?
在设计类时,如果多个类拥有相同的成员变量和函数,直接复制会导致大量冗余。例如 Student 和 Teacher 都有姓名、电话等公共信息,也有各自独有的属性。通过提取公共部分为 Person 基类,Student 和 Teacher 作为派生类继承 Person,可以有效减少重复代码。
#include <iostream>
#include <string>
using namespace std;
class Person {
public:
void identity() {
cout << "void identity()" << _name << endl;
}
protected:
string _name = "张三";
int _age = 18;
string _address;
string _tel;
};
class Student : public Person {
public:
void study() {
cout << "void study()" << endl;
}
protected:
int _stuid;
};
class Teacher : public Person {
public:
void teaching() {
cout << "void teaching()" << endl;
}
protected:
string _title;
};
int main() {
Student s;
Teacher t;
s.();
t.();
;
}


