本文演示了 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

程序的运行方式如下:

  1. 创建 Derived 对象: 在 main 函数中,创建了一个 Derived 对象 d,并通过构造函数初始化其私有成员 x 和 y。
  2. Base 类构造函数调用:由于 Derived 类继承自 Base 类,因此 Derived 对象的构造函数会先调用 Base 类的构造函数来初始化 Base 类的私有成员 x。
  3. Derived 类构造函数调用:接着调用 Derived 类的构造函数来初始化 Derived 类的私有成员 y。
  4. 析构函数调用:程序结束时,会自动调用 Derived 类的析构函数,然后调用 Base 类的析构函数。

这个例子展示了 C++ 中继承的机制,以及构造函数和析构函数在类继承中的作用。

C++ 类继承示例:Base 和 Derived 类的构造和析构

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

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