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 的析构函数,再调用 Base 的析构函数。
原文地址: https://www.cveoy.top/t/topic/jN0i 著作权归作者所有。请勿转载和采集!