继承
多重继承
定义
一个派生类具有两个或两个以上的直接基类就是多重继承
- 1 一个子类可以拥有多个父类;
- 2 子类拥有所有父类的成员变量;
- 3 子类继承所有父类的成员函数;
- 4 子类对象可以当作任意父类对象使用;
格式
多重继承派生类的格式
class 派生类名:继承方式1 基类名1,继承方式2 基类名,….
{ 派生类类体 };
多重继承派生类的构造函数格式
派生类名(总参数表):基类名1(参数表1),基类名2(参数表2),…
子对象名(参数表n+1),…//如果有子对象的话
{ 派生类函数体 }
代码示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| #include<iostream> using namespace std; class Base1 { public: Base1(int) { cout << "Base1(int)called" << endl; } Base1() { cout << "Base1()called" << endl; } ~Base1() { cout << "~Base1()called" << endl; } }; class Base2 { public: Base2() { cout << "Base2()called" << endl; } ~Base2() { cout << "~Base2()called" << endl; } }; class Derived :public Base1, Base2 { public: Derived():Base2(),Base1() { cout << "Derived()called" << endl; } Derived(int x) :Base1(x) { cout << "Derived(int)called" << endl; } ~Derived() { cout << "~Derived()called" << endl; } }; int main() { Derived d; Derived d3 = 3;
Derived* d2 = new Derived(); delete d2; return 0; }
|