构造函数与析构函数执行顺序
代码:
#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
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
ABCD的有参构造函数:a:2 b:2 c:2
再去执行mye 类的拷贝构造函数,
打印出mye的拷贝构造函数:
最后执行 dothing 函数输出的那句话,
打印出doThing() my1.a1.a:1
析构函数与构造函数执行的顺序相反
打印出
mye的析构函数。。。
ABCD的析构函数。。。
ABCD的析构函数。。。
mye的析构函数。。。
ABCD的析构函数。。。
ABCD的析构函数。。。
ABCD的析构函数。。。
ABCD的析构函数。。。
mye的析构函数。。。
ABCD的析构函数。。。
ABCD的析构函数。。。