继承的概念及其定义
1.继承的概念
继承(inheritance)机制是面向对象程序设计使代码可以复用的最重要的手段,它允许程序员在保持原有类特性的基础上进行扩展,增加功能,这样产生新的类,称派生类。继承呈现了面向对象程序设计的层次结构, 体现了由简单到复杂的认知过程。以前我们接触的复用都是函数复用,继承是类设计层次的复用
我们举个栗子看一下:
#include<iostream>
#include<string>
using namespace std;
class Person
{
public:
void Print()
{
cout << "name:" << _name << endl;
cout << "age:" << _age << endl;
}
protected:
string _name = "juju";
int _age = 18;
};
//继承后父类的Person的成员(成员函数 + 成员变量)都会变成子类的一部分。
//这里体现出了Student和 Teacher复用了Person的成员。下面我们使用监视窗
//口查看Student和Teacher对象,可以看到变量的复用。调用 Print可以看到成员函数的复用。
class Student :public Person
{
protected:
int _stuid;
};
class Teacher :public Person
{
protected:
int _jobid;
};
int main()
{
Student s;
Teacher t;
s.Print();
t.Print