C++:继承
目录
1 继承的概念及定义
1.1 继承的概念
继承(inheritance)机制是面向对象程序设计使代码可以复用的最重要的手段,它允许我们在保持原有类特性的基础上进行扩展,增加方法(成员函数)和属性(成员变量),这样产生新的类,称派生类。继承呈现了面向对象程序设计的层次结构,体现了由简单到复杂的认知过程。以前接触的函数层次的复用,继承是类设计层次的复用。
下面没有继承之前设计的两个类 Student 和 Teacher,Student 和 Teacher 都有姓名/地址/电话/年龄等成员变量,都有 identity 身份认证的成员函数,设计到两个类里面就是冗余的。当然他们也有一些不同的成员变量和函数,比如老师独有的成员变量是职称,学生的独有成员变量是学号;学生的独有成员函数是学习,老师的独有成员函数是授课。
class Student { public: // 进入校园/图书馆/实验室刷二维码等身份认证 void identity() { cout << "void identity()" << _name << endl; } // 学习 void study() {} protected: string _name = "李四"; // 姓名 string _address; // 地址 string _tel; // 电话 int _age = 18; // 年龄 int _stuid; // 学号 }; class Teacher { public: // 进入校园/图书馆/实验室刷二维码等身份认证 void identity() { cout << "void identity()" << _name << endl; } // 授课 void teaching() {} protected: string _name = "张三"; // 姓名 string _address; // 地址 string _tel; // 电话 int _age = 46; // 年龄 string title; // 职称 };如果把公共的成员和函数都放到 Person 类中,Student 和 Teacher 都继承 Person,就可以复用这些成员和函数,就不需要重复定义了,省去了很多麻烦。
class Person { public: // 进入校园/图书馆/实验室刷二维码等身份认证 void identity() { cout << "void identity()" << _name << endl; } protected: string _name = "李四"; // 姓名 string _address; // 地址 string _tel; // 电话 int _age = 18; // 年龄 }; class Student : public Person { public: // 学习 void study() { //... identity(); } protected: int _stuid; // 学号 }; class Teacher : public Person { public: // 授课 void teaching() { //... } protected: string title; // 职称 }; int main() { Student s; Teacher t; s.identity(); t.identity(); return 0; }1.2 继承定义
1.2.1 定义格式
下面我们看到 Person 是基类,也称作父类。Student 是派生类,也称作子类。

1.2.2 继承基类成员访问方式的变化
| 类成员/继承方式 | public 继承 | protected 继承 | private 继承 |
| 基类的 public 成员 | 派生类的 public 成员 | 派生类的 protected 成员 | 派生类的 private 成员 |
| 基类的 protected 成员 | 派生类的 protected 成员 | 派生类的 protected 成员 | 派生类的 private 成员 |
| 基类的 private 成员 | 在派生类中不可见 | 在派生类中不可见 | 在派生类中不可见 |
1. 基类 private 成员在派生类中无论以什么方式继承都是不可见的。这里的不可见是指基类的私有成员还是被继承到了派生类对象中,但是语法上限制派生类对象不管在类里面还是类外面都不能去访问它。
2. 基类 private 成员在派生类中是不能被访问,如果基类成员不想在类外直接被访问,但需要在派生类中能访问,就定义为 protected。可以看出保护成员限定符是因继承才出现的。
3. 对上面的表格进行总结就会发现,基类的私有成员在派生类都是不可见的。基类的其他成员在派生类的访问方式==Min(成员在基类的访问限定符,继承方式),public > protected > private。
4. 使用关键字 class 时默认的继承方式是 private,使用 struct 时默认的继承方式是 public,不过最好显示的写出继承方式。
5. 在实际运用中一般使用都是 public 继承,几乎很少使用 protected/private 继承,也不提倡使用 protected/private 继承,因为 protected/private 继承下来的成员都只能在派生类的类里面使用,实际中扩展维护性不强。
class Person { public: void Print() { cout << _name << endl; cout << _age << endl; } protected: string _name = "李四"; // 姓名 private: int _age = 10; // 年龄 }; //// 公有继承 //class Student : public Person //{ //public: // void func() // { // // 基类的私有成员不可见,但是都被继承下来了 // //cout << _age << endl; // _name = "王五"; // 父类保护成员可用 // Print(); // } // //protected: // int _stdnum = 2; // 学号 //}; //// 私有继承 //class Student : private Person //{ //public: // void func() // { // // 基类的私有成员不可见,但是都被继承下来了 // //cout << _age << endl; // _name = "王五"; // 父类保护成员可用 // Print(); // } // //protected: // int _stdnum = 2; // 学号 //}; // 私有继承 class Student : protected Person { public: void func() { // 基类的私有成员不可见,但是都被继承下来了 //cout << _age << endl; _name = "王五"; // 父类保护成员可用 Print(); } protected: int _stdnum = 2; // 学号 }; int main() { Student s; s.func(); // 只能共有继承使用 //s.Print(); // 私有和保护继承这里就不可用了,只能在子类使用 // 父类的保护成员只能在子类的内部使用,不能在外部使用 //s._name; return 0; }1.3 继承模板
namespace room { // stack和vector的关系,既符合is-a,也符合has-a template<class T> class stack : public std::vector<T> { public: void push(const T& x) { // 基类是类模板时,需要指定一下类域, // 否则编译报错:error C3861: “push_back”: 找不到标识符 // 因为stack<int>实例化时,也实例化vector<int>了 // 但是模版是按需实例化,push_back等成员函数未实例化,所以找不到 vector<T>::push_back(x); //push_back(x); } void pop() { vector<T>::pop_back(); } const T& top() { return vector<T>::back(); } bool empty() { return vector<T>::empty(); } }; } int main() { room::stack<int> st; //st.push_back(1); st.push(1); st.push(2); st.push(3); while (!st.empty()) { cout << st.top() << " "; st.pop(); } return 0; }2 基类和派生类间的转换
- public 继承的派生类对象可以赋值给基类的指针/基类的引用。这里有个形象的说法叫切片或者切割。寓意把派生类中基类那部分切出来,基类指针或引用指向的是派生类中切出来的基类那部分。
- 基类对象不能赋值给派生类对象。
- 基类的指针或者引用可以通过强制类型转换赋值给派生类的指针或者引用。但是必须是基类的指针是指向派生类对象时才是安全的。这里基类如果是多态类型,可以使用 RTTI(Run-Time Type Information)的 dynamic_cast 来进行识别后进行安全转换。

class Person { protected: string _name = "李四"; int _id = 1; }; class Student : public Person { public: void func() { // 如果父类和子类的变量名相同,那么使用的是子类的变量 cout << _id << endl; } protected: int _stunum = 1; // 学号 int _id = 2; }; int main() { Student s; s.func(); // 切片,把子类的父类那一部分切下来 Person* ptr = &s; Person& ref = s; return 0; }3 继承中的作用域
3.1 隐藏规则
1. 在继承体系中基类和派生类都有独立的作用域;
2. 派生类和基类中有同名成员,派生类成员将屏蔽基类对同名成员的直接访问,这种情况叫隐藏;(在派生类成员函数中,可以使用 基类::基类成员 显示访问)
3. 需要注意的是如果是成员函数的隐藏,只需要函数名相同就构成隐藏;
4. 注意实际中在继承体系里面最好不要定义同名成员。
class A { public: void func() { cout << "func()" << endl; } }; class B : public A { public: void func(int i) { cout << "func(int i)" << endl; } }; int main() { B b; b.func(10); // 这里调用的是子类的 func //b.func(); // 这里会报错,因为同名函数,子类会把父类的同名函数隐藏 b.A::func();// 要这样使用,指明作用域 return 0; }class Person { protected: string _name = "李四"; int _id = 1; }; class Student : public Person { public: void func() { cout << Person::_id << endl; // 强行使用父类的变量 cout << _id << endl; } protected: int _stunum = 1; // 学号 int _id = 2; }; int main() { Student s; s.func(); return 0; }4 派生类的默认成员函数
4.1 4个常见默认成员函数
6个默认成员函数,默认的意思就是指我们不写,编译器会帮我们自动生成一个,那么在派生类中,这几个成员函数是如何生成的呢?
1. 派生类的构造函数必须调用基类的构造函数初始化基类的那一部分成员。如果基类没有默认的构造函数,则必须在派生类构造函数的初始化列表阶段显式调用;
2. 派生类的拷贝构造函数必须调用基类的拷贝构造完成基类的拷贝初始化;
3. 派生类的 operator= 必须要调用基类的 operator= 完成基类的复制。需要注意的是派生类的 operator= 隐藏了基类的 operator=,所以显示调用基类的 operator=,需要指定基类的作用域;
4. 派生类的析构函数会在被调用完成后自动调用基类的析构函数清理基类成员。因为这样才能保证派生类对象先清理派生类成员再清理基类成员的顺序;
5. 派生类对象初始化先调用基类构造再调用派生类构造;
6. 因为多态中一些场景析构函数需要构成重写,重写的条件之一是函数名相同。那么编译器会对析构函数名进行特殊处理,处理成 destructor(),所以基类析构函数不加 virtual 的情况下,派生类析构函数和基类析构函数构成隐藏关系。


class Person { public: /*Person(const char* name = "peter") {}*/ Person(const char* name) : _name(name) { cout << "Person()" << endl; } // Person& 这里切片子类 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 num) // : _name(name) // 这里要指明类域 // , _num(num) //{} Student(const char* name, int num) : Person(name) // 会切片 , _num(num) {} // 拷贝构造 Student(const Student& s) : Person(s) // 会切片 , _num(s._num) { // 深拷贝要自己写,一般默认的就够用 } Student& operator=(const Student& s) { // 深拷贝 需要自己写 if (this != &s) { // 这里要指明类域,否则子类会把父类的 operator= 隐藏,然后调用自己,一直递归,导致栈溢出 Person::operator=(s); _num = s._num; } return *this; } ~Student() { // 不需要显示调用,保证析构时,先子后父 //Person::~Person(); delete[] _ptr; // 子类析构结束后,会自动调用父类的析构 } protected: int _num = 1; // 学号 int* _ptr = new int[10]; // 这里有资源要释放,就必须自己写析构函数 }; int main() { Student s1("jack", 10); Student s2(s1); Student s3("rose", 17); s1 = s3; return 0; }4.2 实现一个不能被继承的类
⽅法1:基类的构造函数私有,派⽣类的构成必须调⽤基类的构造函数,但是基类的构成函数私有化以后,派⽣类看不⻅就不能调⽤了,那么派⽣类就⽆法实例化出对象。
⽅法2:C++11新增了⼀个final关键字,final修改基类,派⽣类就不能继承了。
// 实现一个不能被继承的类 // C++11的做法:类后面加一个 final class Base { public: void func1() { cout << "Base::func1()" << endl; } protected: int _a = 1; private: // C++98的做法:基类的构造的私有化 // 这样做不好,用的时候会报错,不用的时候逃过编译器检查 // 所以有了上面 C++11 的做法 Base() {} }; class Derive : public Base { public: void func2() { cout << "Derive::func2()" << endl; } protected: int _b = 2; }; // 实现一个不能被继承的类 // C++11的做法:类后面加一个 final class Base final { public: void func1() { cout << "Base::func1()" << endl; } protected: int _a = 1; private: // C++98的做法:基类的构造的私有化 // 这样做不好,用的时候会报错,不用的时候逃过编译器检查 // 所以有了上面 C++11 的做法 Base() {} }; class Derive : public Base { public: void func2() { cout << "Derive::func2()" << endl; } protected: int _b = 2; }; int main() { //Derive d; return 0; }5 继承和友元
class Student; // 声明 class Person { public: friend void Display(const Person& p, const Student& s); protected: string _name = "lisi"; // 姓名 }; class Student : public Person { public: friend void Display(const Person& p, const Student& s); protected: int _stuNum = 1; // 学号 }; void Display(const Person& p, const Student& s) { cout << p._name << endl; cout << s._stuNum << endl; } int main() { Person p; Student s; // 编译报错:error C2248: “Student::_stuNum”: 无法访问 protected 成员(在“Student”类中声明) // 解决方案:Display 也变成 Student 的友元即可 Display(p, s); return 0; }6 继承与静态成员
基类定义了 static 静态成员,则整个继承体系⾥⾯只有⼀个这样的成员。⽆论派⽣出多少个派⽣类,都只有⼀个 static 成员实例。
class Person { public: string _name; static int _count; }; int Person::_count = 10; // 静态成员变量要在类外初始化 class Student : public Person { protected: int _stuNum = 1; // 学号 }; int main() { Person p; Student s; // 虽然子类继承了父类,但是两个 name 是不一样的 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; }7 多继承及其菱形继承问题
7.1 继承模型
单继承:⼀个派⽣类只有⼀个直接基类时称这个继承关系为单继承。
多继承:⼀个派⽣类有两个或以上直接基类时称这个继承关系为多继承,多继承对象在内存中的模型是,先继承的基类在前⾯,后⾯继承的基类在后⾯,派⽣类成员在放到最后⾯。
菱形继承:菱形继承是多继承的⼀种特殊情况。菱形继承的问题,从下⾯的对象成员模型构造,可以看出菱形继承有数据冗余和⼆义性的问题,在 Assistant 的对象中 Person 成员会有两份。⽀持多继承就⼀定会有菱形继承,像 Java 就直接不⽀持多继承,规避掉了这⾥的问题,所以实践中我们也是不建议设计出菱形继承这样的模型的。

class Person { public: string _name; // 姓名 }; // 加 virtual 为了避免菱形继承,避免冗余和二义性 class Student : virtual public Person { protected: int _num = 1; // 学号 }; class Teacher : virtual public Person { protected: int _id = 1; // 工号 }; class Assistant : public Student, public Teacher { protected: string _majorCourse; // 主修课程 }; int main() { // 不加 virtual // 编译报错:error C2385: 对“_name”的访问不明确 Assistant a; a._name = "Peter"; // 如果不加 virtual // 就需要显示指定访问那个基类的成员可以解决二义性的问题,但是数据荣誉问题无法解决 a.Student::_name = "wangwu"; a.Teacher::_name = "zhanssan"; return 0; }7.2 虚继承
很多⼈说C++语法复杂,其实多继承就是⼀个体现。有了多继承,就存在菱形继承,有了菱形继承就有菱形虚拟继承,底层实现就很复杂,性能也会有⼀些损失,所以最好不要设计出菱形继承。多继承可以认为是C++的缺陷之⼀,后来的⼀些编程语⾔都没有多继承,如Java。
class Person { public: Person(const char* name) : _name(name) {} string _name; // 姓名 }; class Student : virtual public Person { public: Student(const char* name, int num) : Person(name) // 虽然父类的构造会初始化 _name,不会走这里的 _name,但是这里也要写,不写会报错,因为还有这个类单独构造对象的情况 , _num(num) {} protected: int _num; // 学号 }; class Teacher : virtual public Person { public: Teacher(const char* name, int id) : Person(name) // 虽然父类的构造会初始化 _name,不会走这里的 _name,但是这里也要写,不写会报错,因为还有这个类单独构造对象的情况 , _id(id) {} protected: int _id; // 工号 }; class Assistant : public Student, public Teacher { public: Assistant(const char* name1, const char* name2, const char* name3) : Person(name3) , Student(name1, 1) , Teacher(name2, 2) {} protected: string _majorCourse; // 主修课程 }; int main() { // 这里 a 对象中 _name 是 "王五" // 为什么? // 因为 Assistant 先初始化 name3,构造先走的是父类的 Person // 这里的初始化列表的顺序与顺序无关 Assistant a("张三", "李四", "王五"); return 0;}我们可以设计出多继承,但是不建议设计出菱形继承,因为菱形虚拟继承以后,⽆论是使⽤还是底层都会复杂很多。当然有多继承语法⽀持,就⼀定存在会设计出菱形继承,像Java是不⽀持多继承的,就避开了菱形继承。
class Person { public : Person(const char* name) : _name(name) {} string _name; // 姓名 }; class Student : virtual public Person { public : Student(const char* name, int num) : Person(name) , _num(num) {} protected: int _num; //学号 }; class Teacher : virtual public Person { public : Teacher(const char* name, int id) : Person(name) , _id(id) {} protected: int _id; // 职⼯编号 }; // 不要去玩菱形继承 class Assistant : public Student, public Teacher { public : Assistant(const char* name1, const char* name2, const char* name3) : Person(name3) , Student(name1, 1) , Teacher(name2, 2) {} protected: string _majorCourse; // 主修课程 }; int main() { // 思考⼀下这⾥a对象中_name是"张三", "李四", "王五"中的哪⼀个? Assistant a("张三", "李四", "王五"); return 0; }7.4 IO库中的菱形继承

template<class CharT, class Traits = std::char_traits<CharT>> class basic_ostream : virtual public std::basic_ios<CharT, Traits> {}; template < class CharT, class Traits = std::char_traits<CharT>> class basic_istream : virtual public std::basic_ios<CharT, Traits> {};8 继承和组合
• public继承是⼀种is-a的关系。也就是说每个派⽣类对象都是⼀个基类对象。
• 组合是⼀种has-a的关系。假设B组合了A,每个B对象中都有⼀个A对象。
• 继承允许你根据基类的实现来定义派⽣类的实现。这种通过⽣成派⽣类的复⽤通常被称为⽩箱复⽤(white-box reuse)。术语“⽩箱”是相对可视性⽽⾔:在继承⽅式中,基类的内部细节对派⽣类可⻅。继承⼀定程度破坏了基类的封装,基类的改变,对派⽣类有很⼤的影响。派⽣类和基类间的依赖关系很强,耦合度⾼。
• 对象组合是类继承之外的另⼀种复⽤选择。新的更复杂的功能可以通过组装或组合对象来获得。对象组合要求被组合的对象具有良好定义的接⼝。这种复⽤⻛格被称为⿊箱复⽤(black-box reuse),因为对象的内部细节是不可⻅的。对象只以“⿊箱”的形式出现。组合类之间没有很强的依赖关系,耦合度低。优先使⽤对象组合有助于你保持每个类被封装。
• 优先使⽤组合,⽽不是继承。实际尽量多去⽤组合,组合的耦合度低,代码维护性好。不过也不太那么绝对,类之间的关系就适合继承(is-a)那就⽤继承,另外要实现多态,也必须要继承。类之间的关系既适合⽤继承(is-a)也适合组合(has-a),就⽤组合。
// Tire(轮胎)和Car(⻋)更符合has-a的关系 class Tire { protected: string _brand = "Michelin"; // 品牌 size_t _size = 17; // 尺⼨ }; class Car { protected: string _colour = "⽩⾊"; // 颜⾊ string _num = "xxxx"; // ⻋牌号 Tire _t1; // 轮胎 Tire _t2; // 轮胎 Tire _t3; // 轮胎 Tire _t4; // 轮胎 }; class BMW : public Car { public: void Drive() { cout << "好开-操控" << endl; } }; // Car和BMW/Benz更符合is-a的关系 class Benz : public Car { public: void Drive() { cout << "好坐-舒适" << endl; } }; template<class T> class vector {}; // stack和vector的关系,既符合is-a,也符合has-a template<class T> class stack : public vector<T> {}; template<class T> class stack { public : vector<T> _v; }; int main() { return 0; }