1.继承的概念
继承(inheritance)机制是面向对象程序设计使代码可以复用的最重要的手段,它允许我们在保持原有类特性的基础上进行扩展,增加方法(成员函数)和属性(成员变量),这样产⽣新的类,称派生类。继承呈现了面向对象程序设计的层次结构,体现了由简单到复杂的认知过程。以前我们接触的函数层次的复用,继承是类设计层次的复用。
接下来我将会举一个经典的继承的代码例子:
cpp
#include<iostream>
#include<string>
using namespace std;
class person
{
public:
person()
{
}
person(string name, string tel, int age)
{
_name = name;
_tel = tel;
_age = age;
}
void identity()
{
cout << "name:"<<_name << endl;
}
protected:
string _name="张三";
string _tel="4568";
int _age=18;
};
class student:public person
{
public:
student()
{ }
student(string name,string tel,int age,string id)
:person(name, tel, age),
_id (id)
{
}
protected:
string _id = "1713";
};
class teacher :public person
{
public:
teacher()
{
}
teacher(string name,string tel,int age,string title)
:person(name,tel,age)
,_title(title)
{
}
protected:
string _title;
};
int main()
{
student s1;
s1.identity();
teacher t1("李四", "1435", 53, "chinese");
t1.identity();
return 0;
}
如上:我们通过继承的方式,可以减少代码量,通过复用的方式来使我们的代码更加简洁。
2.继承定义:
下⾯我们看到Person是基类,也称作⽗类。Student是派⽣类,也称作⼦类。(因为翻译的原因,所以既叫基类/派⽣类,也叫⽗类/⼦类)

2.1 继承基类成员访问方式的变化
-
- 基类private成员在派生类中是不可见的,意思是,尽管派生类继承了基类的private的成员,但是仍然是不可访问的。
-
- 如果基类成员不想在类外直接被访问,但是想在类内访问,就定义为为protected,就可以到类内访问了。
-
- 基类的私有成员在派生类都是不可见的。而且如果继承后的派生类,在类外想访问派生类的成员,按权限等级 public>protected>private,取继承方式 和 原成员权限 取更严格的那个,就是类外访问子类里的最终权限。
-
- class 继承 struct → 默认 private 继承,struct 继承 class → 默认 public 继承class:成员默认 private,struct:成员默认 public。
-
- 在实际运用中⼀般使用都是public继承因为protetced/private继承下来的成员都只能在派生类的类里面使用,实际中扩展维护性不强。
2.2 继承类模板
代码示例:
cpp
#include<iostream>
#include<vector>
#include<string>
using namespace std;
namespace yjh
{
template<class T>
class stack:public vector<T>
{
public:
void push(const T& x )
{
//this->push_back(x);
vector<T>::push_back(x);
}
void print()
{
for (auto& e : *this)
{
cout << e << " ";
}
cout << endl;
}
};
}
int main()
{
yjh::stack<int> st;
st.push(1);
st.print();
return 0;
}
基类是类模板时,需要指定⼀下类域,否则编译报错:error C3861: "push_back": 找不到标识符,因为stack实例化时,也实例化vector了,但是模版是按需实例化,push_back等成员函数未实例化,所以找不到。
3.基类和派生类间的转换
- public继承的派生类对象可以赋值给基类的指针 / 基类的引用。这里有个形象的说法叫切片或者切割。寓意把派生类中基类那部分切出来,基类指针或引用指向的是派生类中切出来的基类那部分。
- 基类对象不能赋值给派生类对象。
- 基类的指针或者引用可以通过强制类型转换赋值给派生类的指针或者引用。但是必须是基类的指针是指向派生类对象时才是安全的。

cpp
#include<iostream>
#include<string>
using namespace std;
struct person
{
string _name;
string _tel;
int _age;
};
struct student:public person
{
public:
string _id;
};
int main()
{
student s;
// 1.派⽣类对象可以赋值给基类的指针/引⽤
person* pp = &s;
person& rp = s;
// ⽣类对象可以赋值给基类的对象是通过调⽤后⾯会讲解的基类的拷⻉构造完成的
person p = s;
//2.基类对象不能赋值给派⽣类对象,这⾥会编译报错
s = p;
return 0;
return 0;
}
4.继承中的作用域
4.1 隐藏规则
- 在继承体系中基类和派生类都有独立的作用域
- 派生类和基类中有同名成员,派生类成员将屏蔽基类对同名成员的直接访问,这种情况叫隐藏。(在派生类成员函数中,可以使用基类::基类成员 显式访问)
- 需要注意的是如果是成员函数的隐藏,只需要函数名相同就构成隐藏。不管成员函数的参数,没有函数重载的这一说法
- 实际运用中最好不要定义相同的变量和成员函数
代码示例:
cpp
#include<iostream>
#include<string>
using namespace std;
class person
{
public:
int _num = 111;
string _name = "wagnw";
string _tel = "89980";
};
class student :public person
{
public:
int _num = 1234;
void print()
{
cout << _num << endl;
cout << _name << endl;
cout << _tel << endl;
}
};
int main()
{
student s1;
s1.print();
return 0;
}

如上,编译器隐藏了父类里的_num,打印出的是子类的_num。
5. 派生类的默认成员函数
5.1 4个常见的默认成员函数
默认成员函数,默认的意思就是指我们不写,编译器会自动生成一个,那么在派生类中,这几个成员函数是如何生成的呢?
-
- 派生类对象 = 基类部分 + 派生类自己部分
只要创建子类对象,基类那一块成员,必须先初始化。子类构造函数,必须先帮基类完成初始化,如果基类没有默认构造函数,必须在初始化列表中显式调用带参的构造
- 派生类对象 = 基类部分 + 派生类自己部分
-
- 派生类的拷贝构造函数必须调⽤基类的拷贝构造完成基类的拷⻉初始化。
-
- 派生类的operator=必须要调用基类的operator=完成基类的复制。需要注意的是派⽣类的operator=隐藏了基类的operator=,所以显式调用基类的operator=,需要指定基类作⽤域
-
- 子类的 operator= 只会拷贝自己的成员,不会自动拷贝基类成员 → 必须手动调用父类的 operator= 去拷贝基类那部分!
-
- 派生类初始化时,先调用基类的构造,再调用派生类的构造
-
- 派生类清理资源时,先调用派生类的析构,再调用基类的析构
-
- 因为多态中⼀些场景析构函数需要构成重写,重写的条件之⼀是函数名相同

cpp
#include<iostream>
#include<vector>
#include<string>
using namespace std;
class person
{
public:
//默认构造
person(const string name = "sjd")
{
_name = name;
cout << "person(const string name)" << endl;
}
//拷贝构造
person(const person &p)
{
_name = p._name;
cout << "person(const person &p))" << endl;
}
person& operator=(const person& p)
{
if (this != &p)
{
_name = p._name;
}
return *this;
}
~person()
{
cout << "~person()" << endl;
}
protected:
string _name;
};
class student :public person
{
public:
//默认构造
student(const string name, string id="2713")
:person(name)
,_id(id)
{
cout << "student(const string name, string id)" << endl;
}
//拷贝构造
student(const student& s)
:person(s)
, _id(s._id)
{
cout << "student(const student& s)" << endl;
}
student& operator=(student& s)
{
if (this != &s)
{
_name = s._name;
_id = s._id;
}
}
~student()
{
cout << "~student()" << endl;
}
protected:
string _id;
};
int main()
{
student s1("yjh");
student s2("you", "19");
student s3(s2);
return 0;
}

5.2 实现⼀个不能被继承的类
- 方法1:基类的构造函数私有,派生类的构成必须调⽤基类的构造函数,但是基类的构造函数私有化以后,派生类看不见就不能调用了,那么派生类就无法实例化出对象。
- 方法2:C++11新增了⼀个final关键字,final修改基类,派生类就不能继承了。
cpp
#include<iostream>
#include<string>
using namespace std;
class person final
{
public:
person()
{
}
protected:
int _num;
};
class student :public person
{
public:
student()
{
}
protected:
int _id;
};

6. 继承与友元
友元关系不能继承,也就是说基类友元不能访问派生类私有和保护成员 。
cpp
#include<iostream>
#include<vector>
#include<string>
using namespace std;
class student;
class person
{
friend void Display(const person& p, const student& s);
public:
person()
{
}
protected:
int _num = 8;
};
class student :public person
{
public:
student()
{
}
protected:
int _id = 1;
};
void Display(const person& p, const student& s)
{
cout << p._num << endl;
cout << s._id << endl;
}
int main()
{
person p;
student s;
Display(p, s);
return 0;
}

解决方案:Display也变成Student 的友元即可
基类的友元,只拿到了基类的访问权限,没有任何资格访问派生类的私有 / 保护成员;且 C++ 语法强行规定:友元关系不能被继承、不能被传递。
7. 继承与静态成员
基类定义了static静态成员,则整个继承体系⾥⾯只有⼀个这样的成员。无论派生出多少个派生类,都只有一个static成员实例。
cpp
#include<iostream>
#include<vector>
#include<string>
using namespace std;
class person
{
public:
string _name = "zhang san";
static int i;
};
class student:public person
{
protected:
int _id = 5;
};
int person::i = 2;
int main()
{
person p;
student s;
cout << &p.i << endl;
cout << &s.i << endl;
cout << &p._name << endl;
cout << &s._name << endl;
return 0;
}

我们发现父类和子类的静态成员变量i地址都是一样的,说明只有一个实例。
8. 多继承及其菱形继承问题
8.1 继承模型
- 单继承:⼀个派生类只有⼀个直接基类时称这个继承关系为单继承
- 多继承:⼀个派生类有两个或以上直接基类时称这个继承关系为多继承,多继承对象在内存中的模型是,先继承的基类在前面,后面继承的基类在后面,派生类成员在放到最后面。
- 菱形继承:菱形继承是多继承的⼀种特殊情况。菱形继承的问题,从下面的对象成员模型构造,可以看出菱形继承有数据冗余和二义性的问题,在Assistant的对象中Person成员会有两份。支持多继承就⼀定会有菱形继承,像Java就直接不支持多继承,规避掉了这里的问题,所以实践中我们也是不建议设计出菱形继承这样的模型的。


cpp
#include<iostream>
#include<vector>
#include<string>
using namespace std;
class person
{
public :
int _a = 1;
};
class student:public person
{
protected:
int _b = 1;
};
class teacher:public person
{
protected:
int _c = 1;
};
class Assistant : public student, public teacher
{
int _d = 1;
};
int main()
{
Assistant a;
//a._a;
a.student::_a;
a.teacher::_a;
return 0;
}

解决方法:指定访问
8.2 虚继承
虚继承相当于是将直接把重复的基类 "合并成一份"。
使用虚继承,可以解决数据冗余和二义性
cpp
#include<iostream>
#include<vector>
#include<string>
using namespace std;
class person
{
public :
int _a = 1;
};
class student:virtual public person
{
protected:
int _b = 1;
};
class teacher:virtual public person
{
protected:
int _c = 1;
};
class Assistant : public student, public teacher
{
int _d = 1;
};
int main()
{
Assistant a;
a._a;
/*a.student::_a;
a.teacher::_a;*/
return 0;
}
多继承中指针偏移问题:

分析 :

在多重继承中,基类子对象的存储顺序严格按照继承声明的顺序排列,所以先继承的,一定是先开辟空间的,所以只要它写在前面,就会排在前面。
p3 是 Derive* 类型,直接指向 d 的起始地址。
所以选C
9. 继承和组合
-
public继承是⼀种is-a的关系。也就是说每个派生类对象都是⼀个基类对象。
-
组合是⼀种has-a的关系。假设B组合了A,每个B对象中都有⼀个A对象。
-
继承允许你根据基类的实现来定义派生类的实现。这种通过生成派生类的复用通常被称为白箱复用(white-box reuse)。术语"白箱"是相对可视性而言:在继承方式中,基类的内部细节对派生类可见 。继承⼀定程度破坏了基类的封装,基类的改变,对派生类有很大的影响。派生类和基类间的依赖关系很强,耦合度高。
-
对象组合是类继承之外的另⼀种复用选择。新的更复杂的功能可以通过组装或组合对象来获得。对象组合要求被组合的对象具有良好定义的接口。这种复用风格被称为黑箱复用(black-box reuse),因为对象的内部细节是不可见的。对象只以"黑箱"的形式出现。 组合类之间没有很强的依赖关系,耦合度低。优先使用对象组合有助于你保持每个类被封装。
-
优先使用组合,而不是继承。实际尽量多去用组合,组合的耦合度低,代码维护性好。不过也不太那么绝对,类之间的关系就适合继承(is-a)那就⽤继承,另外要实现多态,也必须要继承。类之间的关系既适合用继承(is-a)也适合组合(has-a),就用组合。
cpp
#include<iostream>
#include<vector>
#include<string>
using namespace std;
class tire
{
protected:
size_t _size;
};
//has-a
class car
{
protected:
size_t _price;
tire t1;
tire t2;
tire t3;
tire t4;
};
//is-a
class Benz :public car
{
public:
void Drive()
{
cout << "comfort" << endl;
}
};
//既符合is-a 又符合has-a
template<class T>
class stack:public vector<T>
{
public:
void push(const T&x)
{
this->pop_back(x);
//vector<T>::push_back(x);
}
};
template<class T>
class stack
{
public:
vector<T>t;
void push(const T&x)
{
t.push_back(x);
}
};
int main()
{
return 0;
}