private继承

1、子类对象无法转换为父类对象
image.png
2、意味着“根据某物实现出”,Base成分在Derived对象里都是private访问属性,因为Derived对象为了采用Base已经具备的特性,Base成分是Derived对象实现的细枝末节,Derived对象根据Base对象实现出来。
3、继承自父类的每一样东西到了子类都是private成分,Base成分都是实现细节而已,所以private继承意味着只有实现被继承,而不是接口被继承
4、

  1. #include<iostream>
  2. class Base {
  3. public:
  4. Base(int x) : x(x) {}
  5. protected:
  6. int x;
  7. };
  8. class Derived : private Base {
  9. public:
  10. Derived(int x) : Base(x) {}
  11. void func1() {
  12. std::cout << x << std::endl;
  13. }
  14. };
  15. int main() {
  16. Derived d(4);
  17. d.func1();
  18. return 0;
  19. }

image.png

private继承的Derived类可以访问Base类的protected成员
5、private继承也可以重新定义virtual函数

版本一 private继承

  1. class Timer {
  2. public:
  3. //每调用Widget的成员函数,就调用一次onTick,记录调用成员函数的次数
  4. virtual void onTick() const { …… }
  5. };
  6. class Widget : private Timer { …… };

为什么不是public继承?因为Widget并不是Timer,容易造成接口被误用

版本二 复合

  1. class Timer {
  2. public:
  3. virtual void onTick() const { …… }
  4. };
  5. class Widget {
  6. private:
  7. Timer* wt;
  8. };

版本二优点

1、降低编译依存性:版本一Widget被编译时,必须能看见Timer的定义,即#include “Timer.h”
image.pngimage.png
必须看见Base的定义
相反版本二Widget需要WidgetTimer对象时,如果是指针的话,只需要class WidgetTimer声明即可
2、可以阻止Widget派生类重新定义virtual函数
如果想阻止Widget的派生类不重新定义virtual void onTick()函数,版本一不可以,哪怕是private继承,哪怕不调用这个函数
版本二可以做到,因为派生类无法取到Timer对象

版本一优点 - EBO

  1. class Empty {};
  2. class Derived : private Empty {
  3. public:
  4. int x;
  5. };

sizeof(Derived) = 4;

  1. class Empty {}; //sizeof(Empty) = 1
  2. class Derived {
  3. public:
  4. Empty e;
  5. int x;
  6. };

sizeof(Derived) > 4
1、EBO只在单一继承里存在,多重继承不行
2、Empty Class并不是单纯的Empty,含有typedef enum static non-virtual