继承与组合混搭情况下,构造析构的调用原则
- 先构造父类,再构造成员变量、最后构造自己
- 先析构自己,在析构成员变量、最后析构父类
- 先构造的对象,后释放
示例
#include <iostream>
using namespace std;
class Object
{
public:
Object(int m1, int m2)
{
this->m1 = m1;
this->m2 = m2;
cout << "Object 构造函数被调用" << endl;
}
~Object()
{
cout << "Object 析构函数被调用" << endl;
}
private:
int m1;
int m2;
};
class Parent
{
public:
Parent(int a, int b)
{
this->a = a;
this->b = b;
cout << "parent 构造函数被调用" << endl;
}
~Parent()
{
cout << "parent 析构函数被调用" << endl;
}
void printP()
{
printf ("a = %d, b = %d\n", a, b);
}
private:
int a;
int b;
};
class Child :public Parent
{
public:
Child() : Parent(1,2), o1(1,2), o2(3,4)
{
c = 0;
cout << "Child 构造函数被调用" << endl;
}
~Child()
{
cout << "Child 析构函数被调用" << endl;
}
void printC()
{
printf ("c = %d\n", c);
}
private:
int c;
Object o1;
Object o2;
};
int main()
{
Child c;
cout << "sizeof Child " << sizeof Child << endl;
return 0;
}
执行结果:
parent 构造函数被调用
Object 构造函数被调用
Object 构造函数被调用
Child 构造函数被调用
sizeof Child 28
Child 析构函数被调用
Object 析构函数被调用
Object 析构函数被调用
parent 析构函数被调用