构造函数执行顺序
1.基类构造函数(如有多个则按基类声明顺序从左到右)
2.成员变量构造函数(如果有多个按成员变量声明顺序)
3.执行自身构造函数
析构函数执行顺序(与构造相反)
1.自身析构
2.成员析构(与声明顺序相反)
3.基类析构(从右自左)
#include <iostream>
using namespace std;
class B
{
public:
int m_b;
public:
B()
{
cout << "B构造" << endl;
}
B(int b)
{
m_b = b;
cout << "B有参构造" << endl;
}
~B()
{
cout << "B析构" << endl;
}
};
class A
{
public:
int m_a;
B objB;
public:
A()
{
cout << "A构造" << endl;
}
A(int a, int b) : objB(b), m_a(a)
{
cout << "A有参构造" << endl;
}
~A()
{
cout << "A析构" << endl;
}
};
class C
{
public:
int m_c;
public:
C()
{
cout << "C无参构造" << endl;
}
C(int c) : m_c(c)
{
cout << "C有参构造" << endl;
}
~C()
{
cout << "C析构" << endl;
}
};
class D
{
public:
int m_d;
public:
D()
{
cout << "D无参构造" << endl;
}
D(int d) : m_d(d)
{
cout << "D有参构造" << endl;
}
~D()
{
cout << "D析构" << endl;
}
};
class E : public A, public C
{
public:
int m_e;
D objD;
public:
E()
{
cout << "E无参构造" << endl;
}
E(int a, int b, int c, int d) : A(a, b), C(c), objD(d)
{
cout << "E有参构造" << endl;
}
~E()
{
cout << "E析构" << endl;
}
};
int main(int argc, char *argv[])
{
E objE(10, 20, 30, 40);
return 0;
}
输出如下
B有参构造
A有参构造
C有参构造
D有参构造
E有参构造
E析构
D析构
C析构
A析构
B析构
网友评论