继承与派生(11.多继承的执行顺序及构造函数的注意事项)【重点】

1.执行顺序

#include<iostream>
using namespace std;
class A
{
private:
    int x;
public:
    A(int i){x=i;cout<<"it's constructing A class"<<endl;}
    void  showA(){cout<<"it's performance showA function"<<endl;}
    ~A(){cout<<"it's destructing A class"<<endl;}
};
class B
{
public:
    B(){cout<<"it's constructing B class"<<endl;}
    void showB(){cout<<"it's performance showB function"<<endl;}
    ~B(){cout<<"it's destructing B class"<<endl;}
};
class C:public A,public B
{
private:
    A a;
    B b;
public:
    C(int y1,int y2):A(y1),a(y2)
    {cout<<"it's constructing C class"<<endl;}
    void showC()
    {
        showA();
        showB();
        cout<<"it's performance showC function"<<endl;
    }
    ~C(){cout<<"it's destructing C class"<<endl;}
};
int main()
{

    C c(1,2);
    c.showC();
    return 0;
}

演示结果:
在这里插入图片描述

2.多继承的派生类的构造函数的注意事项

1.当派生类是多继承时,要观察他继承的所有基类,只要有一个基类没有无参的构造函数,这个多继承的派生类就必须有构造函数且必须使用初始化成员列表对那个没有无参构造函数的基类进行初始化,要是该基类的对象作为派生类的私有数据成员(即内嵌对象),也要在派生类的构造函数中对其初始化。例如上面例题里派生类C对基类A的操作

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值