以下是简单的 C++ 代码:

#include <iostream>

class Base {
private:
    int x;
public:
    Base(int x) : x(x) {
        std::cout << 'Base constructor' << std::endl;
    }
    ~Base() {
        std::cout << 'Base destructor' << std::endl;
    }
};

class Derived : public Base {
private:
    int y;
public:
    Derived(int x, int y) : Base(x), y(y) {
        std::cout << 'Derived constructor' << std::endl;
    }
    ~Derived() {
        std::cout << 'Derived destructor' << std::endl;
    }
};

int main() {
    Derived d(1, 2);
    return 0;
}

程序的输出结果为:

Base constructor
Derived constructor
Derived destructor
Base destructor

这个结果是因为程序创建了一个 Derived 对象,并且在对象的构造函数中调用了 Base 类的构造函数来初始化 x 成员。因此,程序首先打印出 'Base constructor',然后打印出 'Derived constructor'。接着,程序在 main 函数结束时销毁 Derived 对象,因此程序打印出 'Derived destructor' 和 'Base destructor'。

C++ 继承:Base 和 Derived 类构造函数与析构函数的执行顺序

原文地址: https://www.cveoy.top/t/topic/jN0t 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录