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
所以在主函数调用派生类里对象,会先依次调用基类的构造函数其次是派生类。而之后析构函数的调用则完全相反。
标签:调用,C++,派生类,Mammal,里析构,构造函数 From: https://www.cnblogs.com/drip3775/p/17302913.html