【C++】继承

【C++】继承

目录

一. 概念

二. 基类和派生类对象赋值转换

三. 继承中的作用域

四. 派生类的默认成员函数

1. 构造函数

2. 拷贝构造

3. 赋值重载

4. 析构函数

五. 继承与友元

六. 继承与静态成员

七. 多继承、菱形继承、菱形虚拟继承

虚拟继承解决数据冗余和二义性的原理

八. 继承和组合


一. 概念

继承是类设计层次的复用

语法:Person是父类,也称作基类。Student是子类,也称作派生类


继承关系和访问限定符:

继承以后,保护和私有不一样了

  1. 不可见:基类的私有成员还是被继承到了派生类对象中,但是语法上限制派生类对象不管在类里面还是类外面,都不能去访问它。基类的私有成员在基类中还是能用,在基类外不能用
  2. 如果基类成员不想在类外直接被访问,但需要在 派生类中能访问,就把基类成员定义为protected
  3. 基类的私有成员在子类都是不可见。基类的其他成员在子类的访问方式 == Min(成员在基类的访问限定符,继承方式),public > protected > private

二. 基类和派生类对象赋值转换

不同类型对象赋值要类型转换

int i = 0; double d = i;
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() { Person p; Student s; // s = p; 错:父类不能赋值给子类 // s = (Student)p; 强转也不行 p = s; Person p1 = s; return 0; }

子类对象可以赋值给父类的对象、指针、引用
子类赋值给父类对象
,语法上特殊处理,没有发生类型转换,而是赋值兼容(切割、切片)
把子类里,父类那部分切出来,拷贝给父类

怎么证明没有发生类型转换?用另一种语法

p2 变成子类中,父类那一部分的别名

把父类的成员变量放成 public

三. 继承中的作用域

域都是编译时,查找规则的概念

定义了一个类,就有类域。子类和父类有独立的类域
类和类中有同名成员,子类成员将屏蔽父类对同名成员的直接访问,这种情况叫隐藏, 也叫重定义。(在子类成员函数中,可以使用父类::父类成员显示访问)
父子类域中,如果是成员函数的隐藏,只需要函数名相同就构成隐藏

现实中尽量不要在继承体系里定义同名成员

class Person { public: void fun() { cout << "Person::func()" << endl; } protected: string _name = "小李子"; // 姓名 int _num = 111; // 身份证号 }; // 隐藏/重定义:子类和父类有同名成员,子类的成员隐藏了父类的成员 class Student : public Person { public: void fun(int) { cout << "Student::func(int)" << endl; } void Print() { cout << "姓名:" << _name << endl; cout << _num << endl; // 999 cout << Person::_num << endl; // 111 } protected: int _num = 999; // 学号 }; int main() { Student s; s.Print(); s.fun(1); //s.fun(); 报错 //编译语法检查时,现在子类找func,找到了,要传参数,但你没传 s.Person::fun(); return 0; }

2个 func 构成什么关系?(a)
a、隐藏/重定义         b、重载         c、重写/覆盖         d、编译报错

同一作用域才能构成重载

四. 派生类的默认成员函数

设计理念:父干父的活,子干子的活

1. 构造函数

按以前的理解,子类有2个成员:_name 和 _id

规定:子类的构造函数中,不能在初始化列表显示初始化父类成员。在构造函数体内可以

class Person { public: Person(const char* name = "peter") : _name(name) { cout << "Person()" << endl; } ~Person() { cout << "~Person()" << endl; } protected: string _name; // 姓名 }; class Student : public Person { public: Student(const char* name = "张三", int id = 0) :_id(0) //,_name(name) 报错: “Student”: 非法的成员初始化:“_name”不是基或成员 { } protected: int _id; }; int main() { Student s; return 0; }

没定义父类对象,但调用了父类的构造函数

规定:子类必须调父类的构造函数,初始化父类成员
        默认:在初始化列表自动调用父类的默认构造函数(父类不提供默认构造函数会报错)
        若父类不提供默认构造函数:

class Person { public: Person(const char* name) : _name(name) { cout << "Person()" << endl; } ~Person() { cout << "~Person()" << endl; } protected: string _name; // 姓名 }; class Student : public Person { public: Student(const char* name = "张三", int id = 0) :Person(name) // 比较特殊,类似于定义一个匿名对象 ,_id(0) { } protected: int _id; }; int main() { Student s; return 0; }

不加19行会报错,19行的写法很特殊

调试发现,在初始化列表先走Person(name),说明:继承的成员声明在自己的成员之前
在初始化列表先写_id也可以,因为初始化顺序是按声明顺序来的

2. 拷贝构造

规定:必须调父类的拷贝构造

class Person { public: Person(const char* name = "peter") : _name(name) { cout << "Person()" << endl; } Person(const Person& p) : _name(p._name) { cout << "Person(const Person& p)" << endl; } ~Person() { cout << "~Person()" << endl; } protected: string _name; // 姓名 }; class Student : public Person { public: Student(const char* name = "张三", int id = 0) :Person(name) ,_id(0) { } Student(const Student& s) //:_name(s._name) 报错:: “Student”: 非法的成员初始化:“_name”不是基或成员 :Person(s) ,_id(s._id) { } protected: int _id; }; int main() { Student s1; Student s2(s1); return 0; }

31行,父类拷贝构造要传父类对象,在这里只有子类对象,可以直接传:子类对象可以传给父类对象的指针/引用

如果删去31行,不会报错,但有问题:拷贝构造也是构造函数,构造函数在初始化列表不写,默认不会调拷贝构造函数,默认调默认构造函数

3. 赋值重载

class Person { public: Person(const char* name = "peter") : _name(name) { cout << "Person()" << endl; } Person(const Person& p) : _name(p._name) { cout << "Person(const Person& p)" << endl; } Person& operator=(const Person& p) { cout << "Person operator=(const Person& p)" << endl; if (this != &p) _name = p._name; return *this; } ~Person() { cout << "~Person()" << endl; } protected: string _name; // 姓名 }; class Student : public Person { public: Student(const char* name = "张三", int id = 0) :Person(name) ,_id(0) { } Student(const Student& s) :Person(s) ,_id(s._id) { } Student& operator=(const Student& s) { if (this != &s) { Person::operator=(s); // 构成隐藏,要显示访问 _id = s._id; } return *this; } protected: int _id; }; int main() { Student s1; Student s3("李四", 1); s1 = s3; return 0; }

4. 析构函数

class Person { public: // ...... ~Person() { cout << "~Person()" << endl; } protected: string _name; // 姓名 }; class Student : public Person { public: // ...... ~Student() { //~Person(); 调不到 Person::~Person(); // 有问题 } protected: int _id; }; int main() { Student s1; Student s3("李四", 1); s1 = s3; return 0; }

为什么58行调不到,要指定父类类域?
由于后面多态的原因(具体后面讲),析构函数的函数名被特殊处理了,统一处理成destructor,此时构成隐藏

但此时又有新的问题,总共2个对象,调了4次析构函数

屏蔽59行反而正确了

构造、拷贝、赋值要显示调用
析构函数是个特殊,为保证析构顺序,会自动调

子类对象分开来看,分为父类部分和子类部分

显示调用父类析构,无法保证先子后父的析构顺序
所以子类析构函数完成后,自动调用父类析构,这样就保证了先子后父的析构顺序

为什么要保证先子后父的析构顺序?
因为子类中有可能用到父类成员,父类不可能用到子类

eg:先析构父,子再访问父的成员

class Person { public: Person(const char* name = "peter") : _name(name) { cout << "Person()" << endl; } Person(const Person& p) : _name(p._name) { cout << "Person(const Person& p)" << endl; } Person& operator=(const Person& p) { cout << "Person operator=(const Person& p)" << endl; if (this != &p) _name = p._name; return *this; } ~Person() { cout << "~Person()" << endl; delete _pstr; } protected: string _name; // 姓名 string* _pstr = new string("111111111"); }; class Student : public Person { public: Student(const char* name = "张三", int id = 0) :Person(name) ,_id(0) { } Student(const Student& s) :Person(s) ,_id(s._id) { } Student& operator=(const Student& s) { if (this != &s) { Person::operator=(s); _id = s._id; } return *this; } ~Student() { //Person::~Person(); cout << *_pstr << endl; // 子类中有可能用到父类成员 } protected: int _id; }; int main() { Student s1; Student s3("李四", 1); s1 = s3; return 0; }

如果把 Person::~Person(); 放开:↓

五. 继承与友元

友元关系不能继承,父类友元不能访问子类私有和保护成员

class Student; class Person { friend void Display(const Person& p, const Student& s); protected: string _name; // 姓名 }; class Student : public Person { friend void Display(const Person& p, const Student& s); protected: int _stuNum; // 学号 }; void Display(const Person& p, const Student& s) { cout << p._name << endl; cout << s._stuNum << endl; } int main() { Person p; Student s; Display(p, s); return 0; }

屏蔽掉11行会报错: “Student::_stuNum”: 无法访问 protected 成员(在“Student”类中声明)

六. 继承与静态成员

以前的继承:子类对象中的父类成员,和父类对象成员不是同一个

父类定义了static静态成员,则整个继承体系里面只有一个这样的成员。无论派生出多少个子类,都只有一个static成员实例,在子类中不会单独拷贝一份

eg:↓ 统计Person及子类创建出多少个对象

class Person { public: Person() { ++_count; } //protected: string _name; // 姓名 public: static int _count; // 统计人的个数 }; int Person::_count = 0; class Student : public Person { protected: int _stuNum; // 学号 }; class Graduate : public Student { protected: string _seminarCourse; // 研究科目 }; int main() { Person p; Student s; cout << &p._name << endl; cout << &s._name << endl; cout << &p._count<< endl; cout << &s._count << endl; cout << &Person::_count << endl; cout << &Student::_count << endl; return 0; }

七. 多继承、菱形继承、菱形虚拟继承

实践中可以谨慎用多继承,不要用菱形继承

单继承:一个子类只有一个直接父类时称这个继承关系为单继承

多继承:一个子类有两个或以上直接父类时称这个继承关系为多继承

菱形继承:菱形继承是多继承的一种特殊情况

菱形继承的问题:数据冗余(浪费空间)、二义性(不知道要访问谁)

class Person { public: string _name; // 姓名 int _age; }; class Student : public Person { protected: int _num; //学号 }; class Teacher : public Person { protected: int _id; // 职工编号 }; class Assistant : public Student, public Teacher { protected: string _majorCourse; // 主修课程 }; int main() { Assistant as; as._age = 19; // 报错: 对“_age”的访问不明确 return 0; }

二义性可以被解决,但违背常理

int main() { Assistant as; as.Student::_age = 18; // 指定访问 as.Teacher::_age = 30; return 0; }

祖师爷引入了虚拟继承,解决数据冗余、二义性

class Person { public: string _name; // 姓名 int _age; }; class Student : virtual public Person { protected: int _num; //学号 }; class Teacher : virtual public Person { protected: int _id; // 职工编号 }; class Assistant : public Student, public Teacher { protected: string _majorCourse; // 主修课程 }; int main() { Assistant as; as.Student::_age = 18; as.Teacher::_age = 30; as._age = 19; return 0; }

看着 as 里面有3份,实际是1份

虚拟继承解决数据冗余和二义性的原理

菱形继承:↓

class A { public: int _a; }; class B : public A { public: int _b; }; class C : public A { public: int _c; }; class D : public B, public C { public: int _d; }; int main() { D d; d.B::_a = 1; d.C::_a = 2; d._b = 3; d._c = 4; d._d = 5; return 0; }

菱形虚拟继承:↓

class A { public: int _a; }; class B : virtual public A { public: int _b; }; class C : virtual public A { public: int _c; }; class D : public B, public C { public: int _d; }; int main() { D d; d.B::_a = 1; d.C::_a = 2; d._b = 3; d._c = 4; d._d = 5; d._a = 0; D d1; return 0; }

这样设计有什么用呢?

int main() { D d; d._a = 0; B b; b._a = 2; b._b = 3; B* ptr = &b; ptr->_a++; ptr = &d; ptr->_a++; return 0; }

先取到偏移量,计算 _a 在对象中的地址,再访问

八. 继承和组合

class C { //.... }; // 继承 class D : public C {}; // 组合 class E { private: C _cc; };

继承一般不用 private

继承:白箱复用,父类的内部细节对子类可见;子类对象可以访问父类的 public、protected;父类和子类的耦合度高。改变父类的成员,子类要跟着改

组合:黑箱复用,对象的内部细节不可见;E类只能用 C类的 public 和定义了友元的 protected;耦合度低

实践中多用组合。继承和组合都可以,就用组合;更适合用继承的用继承;实现多态,必须用继承

public继承是 is-a 的关系:每个子类对象一定是父类对象
        eg:教师、学生都是人

组合是 has-a 的关系:E 组合了 C,每个 E对象中都有一个 C对象
        eg:E是车,C是轮胎,每个车都有轮胎

本篇的分享就到这里了,感谢观看,如果对你有帮助,别忘了点赞+收藏+关注
小编会以自己学习过程中遇到的问题为素材,持续为您推送文章

Read more

【C++】unordered系列容器使用及封装

【C++】unordered系列容器使用及封装

目录 一、unordered_map和unordered_set的使用 1. unordered_set系列的使用 1.1 unordered_set和unordered_multiset参考文档 1.2 unordered_set类的介绍 1.3 unordered_set和set的使用差异 1.4 unordered_map和map的使用差异 1.5 unordered_multimap/unordered_multiset 1.6 unordered_xxx的哈希相关接口 二、用哈希表封装myunordered_map和myunordered_set 1. 源码及框架分析 2. 模拟实现unordered_map和unordered_set 2.1 实现出复用哈希表的框架,并支持insert 2.

By Ne0inhk
扒透 STL 底层!map/set 如何封装红黑树?迭代器逻辑 + 键值限制全手撕----《Hello C++ Wrold!》(23)--(C/C++)

扒透 STL 底层!map/set 如何封装红黑树?迭代器逻辑 + 键值限制全手撕----《Hello C++ Wrold!》(23)--(C/C++)

文章目录 * 前言 * map和set的封装 * 底层红黑树的模拟实现 * 迭代器的模拟实现 前言 你是不是也有过这种 “知其然不知其所以然” 的困惑: 用 map 存键值对、用 set 去重排序时很顺手,但一被问 “map 的 [] 怎么既插入又访问”“set 为啥不能改元素”“它们底层的红黑树到底存的啥”,就瞬间卡壳?甚至看 STL 源码时,被 “KeyOfT”“迭代器 ++ 逻辑” 绕得晕头转向? 其实 map 和 set 的本质,就是对红黑树的 “定制化封装” —— 红黑树是 “通用骨架”,map 和 set 通过 “提取键的规则(KeyOfT)”“迭代器权限控制”“键值修改限制”,分别适配了 “键值对存储”

By Ne0inhk
【C++初阶】C++入门相关知识(1):C++历史 & 第一个C++程序 & 命名空间

【C++初阶】C++入门相关知识(1):C++历史 & 第一个C++程序 & 命名空间

🎈主页传送门:良木生香 🔥个人专栏:《C语言》 《数据结构-初阶》 《程序设计》 🌟人为善,福随未至,祸已远行;人为恶,祸虽未至,福已远离 前言:我们在此之前已经学习了C语言和数据结构,明白了C语言的基本概念,同时也学习了初阶的数据结构,现在,我们已经具备了学习初阶c++的能力了,那么,从今天开始,我们就正式进入到C++的学习中了,本专栏会记录下小编的学习C++的历程,有什么讲的不对的地方还请大佬们指出错误,那么,现在我们就正式进入到C++的学习吧 本专栏介绍:在我们之前已经学习过的C语言和数据结构的基础上,我们将会在本C++专栏上继续学习C++语法、STL、以及高阶数据结构 目录 一、C++历史介绍 1.1、起源与诞生(1979~1983) 1.2、核心 1.3发展与完善(

By Ne0inhk

CCF-GESP计算机学会等级考试2025年9月二级C++T2 菱形

B4412 [GESP202509 二级] 菱形 题目描述 小 A 想绘制一个菱形。具体来说,需要绘制的菱形是一个 nnn 行 nnn 列的字符画,nnn 是一个大于 111 的奇数。菱形的四个顶点依次位于第 111 行、第 111 列、第 nnn 行、第 nnn 列的正中间,使用 # 绘制。相邻顶点之间也用 # 连接。其余位置都是 .。 例如,一个 555 行 555 列的菱形字符画是这样的: ..#.. .#.#. #...# .#.#. ..#.. 给定 nnn,请你帮小 A 绘制对应的菱形。 输入格式 一行,一个正整数 nnn。

By Ne0inhk