Chapter 11 Inheritance

  1. 私有继承:

父类的公有成员和私有成员到了子类里全部私有。子类内部可以访问继承过来的公有成员(比如类内函数可以访问),但外部无法直接访问(如直接cout<<a.age())

公有继承:

父类的公有成员和保护成员到了子类里访问属性不变,但类外只能访问公有成员。

保护继承:

父类的公有和保护成员可以在子类内部被访问,但子类外部只能访问公有成员不能访问保护成员。

注意,不论是何种继承方式,父类的私有成员一定是不可访问的。

  1. 子类的构造函数:

ChildClassName(ParameterList):ParentClassName(ParameterList0) { // Initialize new data members in child class } 注意父类的参数列表的形参前面没有类型名

析构函数正常写

  1. 调用序列:父类-子类-子类-父类  类似先穿袜子后穿鞋,先脱鞋后脱袜子。
  2. Invoking Sequence

When a new instance of child class is created,  the constructor of  parent classis invoked first,  then the constructors of  subobjects are invoked,  and then the constructor of  child classis invoked

When an instance of child class is destroyed,

 the destructor of child classis invoked first,  then the destructors of  subobjects are invoked,  and then the destructor of parent classis invoked

  1. 内存分配策略:Minimum Static Space Allocation—Allocate the amount of space necessary for the base classonly. (C++)
  2. 多重继承声明:

class ChildName:[public|private] ParentName1,…, [public|private] ParentNameN{ … };

  1. 多重继承下子类的构造函数:

ChildName(ParameterList) :ParentName1(ParameterList1), … ,ParentNameN(ParameterListN){ … };

  1. Problem with Multiple Inheritance -Name Ambiguity

class X{ public: int f( ); };

class Y{ public: int f( ); int g( ); };

class Z:public X, public Y{ public: int g( ); int h( ); };

Z obj;

obj . f( );  //error 引起歧义 不知道调用哪个

obj . g( );  //

解决方法:作用域运算符

Z obj; obj . X::f( );  // selects f( ) in X

obj . Y::f( );  // selects f( ) in Y

obj . Y:: g( );  // selects g( ) in Y

obj . g( );  // selects g( ) in Z

另一种解决方法:虚基类 适用于三代以上继承存在的情况

原文地址:https://www.cnblogs.com/lipoicyclic/p/13154539.html