C++ 继承:Base 和 Derived 类构造函数与析构函数的调用顺序
C++ 继承:Base 和 Derived 类构造函数与析构函数的调用顺序
本文通过一个简单的 C++ 代码示例,展示了 Base 类和 Derived 类之间的继承关系,以及构造函数和析构函数在对象创建和销毁过程中的调用顺序。
代码示例
#include <iostream>
class Base {
private:
int x;
public:
Base(int x) : x(x) {
std::cout << 'Base constructor called' << std::endl;
}
~Base() {
std::cout << 'Base destructor called' << std::endl;
}
};
class Derived : public Base {
private:
int y;
public:
Derived(int x, int y) : Base(x), y(y) {
std::cout << 'Derived constructor called' << std::endl;
}
~Derived() {
std::cout << 'Derived destructor called' << std::endl;
}
};
int main() {
Derived d(1, 2);
return 0;
}
输出结果
Base constructor called
Derived constructor called
Derived destructor called
Base destructor called
解释
程序的输出结果是这样的,因为在创建 Derived 对象时,首先会调用 Base 类的构造函数,然后再调用 Derived 类的构造函数。在销毁 Derived 对象时,先调用 Derived 类的析构函数,然后再调用 Base 类的析构函数。
总结:
- 在创建派生类对象时,首先会调用基类的构造函数,然后再调用派生类的构造函数。
- 在销毁派生类对象时,首先会调用派生类的析构函数,然后再调用基类的析构函数。
原文地址: https://www.cveoy.top/t/topic/jN0f 著作权归作者所有。请勿转载和采集!