文章目录
c++构造和析构顺序
结论
- 构造顺序:
- 按照继承顺序调用基类的构造函数。
- 按照声明顺序调用成员变量的构造函数。
- 调用派生类的构造函数(体)。
- 析构顺序(与构造顺序完全相反):
- 调用派生类的析构函数(体)。
- 按照声明顺序的反序调用成员变量的析构函数。
- 按照继承顺序的反序调用基类的析构函数。
例子
cpp
#include <iostream>
using namespace std;
class Base1 {
public:
Base1() {
cout << "Base1()" << endl;
}
virtual ~Base1() {
cout << "~Base1()" << endl;
}
};
class Base2 {
public:
Base2() {
cout << "Base2()" << endl;
}
virtual ~Base2() {
cout << "~Base2()" << endl;
}
};
class Member1 {
public:
Member1() {
cout << "Member1()" << endl;
}
~Member1() {
cout << "~Member1()" << endl;
}
};
class Member2 {
public:
Member2() {
cout << "Member2()" << endl;
}
~Member2() {
cout << "~Member2()" << endl;
}
};
class Member3 {
public:
Member3() {
cout << "Member3()" << endl;
}
~Member3() {
cout << "~Member3()" << endl;
}
};
class Dervied : public Base1, public Base2 {
public:
Dervied() : m3(), m1() {
cout << "Dervied()" << endl;
}
~Dervied() {
cout << "~Dervied()" << endl;
}
private:
Member1 m1;
Member2 m2;
Member3 m3;
};
class Dervied2 : public Base2, public Base1 {
public:
Dervied2() : m2(), m3(), m1() {
cout << "Dervied()" << endl;
}
~Dervied2() {
cout << "~Dervied()" << endl;
}
private:
Member1 m1;
Member2 m2;
Member3 m3;
};
int main() {
Base1 *b = new Dervied();
cout << "---------------------" << endl;
delete b;
cout << "---------------------" << endl;
Base1 *b1 = new Dervied2();
cout << "---------------------" << endl;
delete b1;
return 0;
}
输出:
Base1()
Base2()
Member1()
Member2()
Member3()
Dervied()
---------------------
~Dervied()
~Member3()
~Member2()
~Member1()
~Base2()
~Base1()
---------------------
Base2()
Base1()
Member1()
Member2()
Member3()
Dervied()
---------------------
~Dervied()
~Member3()
~Member2()
~Member1()
~Base1()
~Base2()