C++ 继承机制与同名成员隐藏
继承(inheritance)是面向对象编程中代码复用的核心手段。它允许我们在保持基类特性的基础上扩展功能,生成新的派生类。这不仅体现了程序的层次结构,也反映了从简单到复杂的认知过程。
一、什么是继承?
设计两个类 Student 和 Teacher 时,如果它们都有姓名、地址、电话等公共属性,直接定义在各自类中会导致大量冗余。通过引入一个 Person 基类,将公共成员提取出来,利用继承处理,就能避免重复定义。
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.identity();
t.identity();
return 0;
}
二、继承的定义
定义的格式
Person 是基类(父类),Student 是派生类(子类)。继承方式决定了基类成员在派生类中的访问权限。


