一、继承的概念及定义
1.1继承的概念
继承是面向对象程序设计使代码可以复用的重要手段,它允许程序员在保持原有类特性的基础上进行扩展,增加功能,这样产生新的类,称为派生类。继承呈现了面向对象程序设计的层次结构,是类设计层次的复用。
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
class Person{
public:
void print()
{
cout << "name" <<" "<< _name << endl;
cout << "age" <<" "<< _age << endl;
}
protected:
string _name = "peter";
int _age = 18;
};
class student :public Person
{
protected:
int _stuid;//学号
};
class teacher :public Person
{
protected:
int _jobid;//工号
};
int main()
{
student s;
teacher t;
s.print();
t.print();
system("pause");
return 0;
}
调式过程我们可以看出来,访问s,t对象的print函数时,调用的是父类的print函数。说明继承后父类的Person的成员(成员变量+成员函数)都会成为子类的一部分。
运行结果显示,student和teacher都复用了Person的成员。
1.2 继承的定义
1.2.1 定义格式
通过下面的图可以看到Person是父类(基类),teacher是子类(派生类),public是继承的方式。
1.2.2 继承关系和访问限定符
1.2.3 继承基类成员访问方式的变化
我们可以发现:
1.基类privated成员在派生类中无论以什么方式继承都是不可见的。
2.在实际运用中一般使用的都是public继承,因为protected/privated继承下来的成员都只能在派生类的类里面使用,扩展维护性不强。
class Person