C++派生类里析构函数和构造函数的调用顺序

C++派生类里析构函数和构造函数的调用顺序

1.定义一个哺乳类Mammal,在由此派生出狗类Dog,定义一个Dog类的对象,观察基类和派生类的构造函数与析构函数的调用顺序。

#include<bits/stdc++.h>
using namespace std;
class Mammal {
public:
	Mammal() {
		cout << "constructed M" << endl;
	}
	~Mammal() {
		cout << "destroyed M" << endl;
	}
private:
};
class Dog :Mammal {
public:
	Dog() {
		cout << "constructed D" << endl;
	}
	~Dog() {
		cout << "destroyed D" << endl;
	}

};
int main() {
	Dog d1;
}

结果如下:

constructed M
constructed D
destroyed D
destroyed M

所以在主函数调用派生类里对象,会先依次调用基类的构造函数其次是派生类。而之后析构函数的调用则完全相反。

posted @ 2023-04-10 14:50  笠大  阅读(32)  评论(0编辑  收藏  举报