c++中, 构造函数和析构函数的执行顺序

c++中, 构造函数和析构函数的执行顺序。

在面试和实际编程中,会遇到多重继承的问题。顺序很重要,理解着记。
看下例子:

#include <iostream>
using namespace std;

class Base
{
public :
    int x0;
    Base(int a = 0)
    {
        x0 = a;
        cout<<"in Base() \t"<<x0<<endl;
    }
    ~Base()
    {
        cout<<"in ~Base() \t"<<x0+1<<endl;
    }
};

class Base1: public Base
{
public :
    int x1;
    Base1(int b, int a = 0): Base(a)
    {
        x1 = b;
        cout<<"in Base1() \t"<<x1<<endl;
    }
    ~Base1()
    {
        cout<<"in ~Base1() \t"<<x1+10<<endl;
    }
};

class Base2: public Base
{
public :
    int x2;
    Base2(int b, int a = 1): Base(a)
    {
        x2 = b;
        cout<<"in Base2() \t"<<x2<<endl;
    }
    ~Base2()
    {
        cout<<"in ~Base2() \t"<<x2+100<<endl;
    }
};

class Base3: public Base2, Base1
{
public :
    int x3;
    Base3(int a, int b, int c, int d): Base1(b), Base2(c)
    {
        x3 = d;
        cout<<"in Base3() \t"<<x3<<endl;
    }
    ~Base3()
    {
        cout<<"in ~Base3() \t"<<x3+1000<<endl;
    }

};

int main()
{
	Base3 b3(1,2,3,4);
	return 0;
}

这种多重继承的顺序,主要看以下几个关键点:
(1)Base3的定义,和继承顺序。
像例子那样的类型,class Base3: public Base2, Base1。
构造函数执行顺序看定义的顺序,而不是看Base3构造函数的 “:” 后面的顺序,因此是 Base2() -> Base1() -> Base3()内容。
而Base2()和Base1()分别用了Base()。
完整的顺序:
Base();
Base2();
Base();
Base1();

Base3()内容;

同理,析构的顺序正好是构造函数的逆序。当b3对象析构时,析构顺序。
~Base3();
~Base1();
~Base();
~Base2();
~Base();

(2)构造函数和析构函数的内容。
这个很简单了。

掌握了以上2点,就可以知道输出的结果。

输出结果:

in Base() 1
in Base2() 3
in Base() 0
in Base1() 2
in Base3() 4
in ~Base3() 1004
in ~Base1() 12
in ~Base() 1
in ~Base2() 103
in ~Base() 2
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值