构造函数与析构函数执行顺序

构造函数与析构函数执行顺序
代码:
#include <iostream>
using namespace std;

class ABCD
{
public:
    ABCD(int a,int b,int c)
    {
        this->a = a;
        this->b = b;
        this->c = c;
        cout<<"ABCD的有参构造函数:"<<"a:"<<a<<" b:"<<b<<" c:"<<c<<endl;
    }
    
    ABCD(const ABCD& obj)
    {
        this->a = obj.a;
        this->b = obj.b;
        this->c = obj.c;
        cout<<"ABCD的拷贝构造函数:"<<"a:"<<a<<" b:"<<b<<" c:"<<c<<endl;
    }

    ~ABCD()
    {
        cout<< "ABCD的析构函数。。。" <<endl;
    }

    int getA() 
    {
        return this->a;
    }
private:
    int a;
    int b;
    int c;
};

class mye
{
public:
    mye():a1(1,1,1),a2(2,2,2),m(100)
    {
        cout<<"mye的无参构造函数:"<<endl;
    }

    mye(const mye& obj):a1(1,1,1),a2(2,2,2),m(100)
    {
        cout<<"mye的拷贝构造函数:"<<endl;
    }
    ~mye()
    {
        cout<< "mye的析构函数。。。" <<endl;
    }
public:
    ABCD& getA1()
    {
        return a1;
    }

private:
    ABCD a1;
    ABCD a2;
    const int m;
};

int dothing(mye my1)
{
    cout << "doThing() my1.a1.a:" << my1.getA1().getA() <<endl;
    return 0;
}

int run2()
{
    mye mye1;
    dothing(mye1);
    return 0;
}

void main()
{
   run2();
   system("pause");
}

执行结果:

执行流程:

main 函数调用 run2函数,在run2函数里,执行 mye mye1;
即执行  mye(const mye& obj):a1(1,1,1),a2(2,2,2),m(100)这句话,
先对 ABCD a1 和 ABCD a2 初始化,分别执行ABCD类的有参构造函数,
打印出ABCD的有参构造函数:a:1 b:1 c:1
           ABCD的有参构造函数:a:2 b:2 c:2
再去执行mye 类的无参构造函数,
打印出mye的无参构造函数:
执行 dothing(mye1)这句话,(mye1是个元素,进入 mye 类,调用 mye 类的拷贝构造函数),先对 ABCD a1 和 ABCD a2 初始化,分别执行ABCD类的有参构造函数,
打印出ABCD的有参构造函数:a:1 b:1 c:1
           ABCD的有参构造函数:a:2 b:2 c:2
再去执行mye 类的拷贝构造函数,
打印出mye的拷贝构造函数:
最后执行 dothing 函数输出的那句话,
打印出doThing() my1.a1.a:1
析构函数与构造函数执行的顺序相反
打印出
           mye的析构函数。。。
          ABCD的析构函数。。。
          ABCD的析构函数。。。
          mye的析构函数。。。
          ABCD的析构函数。。。
          ABCD的析构函数。。。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值