c++ - 了解 C++ 析构函数在派生类中的行为

标签 c++ inheritance destructor

我正在阅读 Stroustrup 的 C++ 编程书中的一段代码。

class Vector_container : public Container {
    Vector v;
public:    
    // Vector_container implements Container
    Vector_container(int s) : v(s) { } // Vector of s elements
    ~Vector_container() {}

    double& operator[](int i) { return v[i]; }
    int size() const { return v.size(); }    
};

作者接着说

  1. The destructor (~Vector_container()) overrides the base class destructor (~Container()).
  2. Note that the member destructor (~Vector()) is implicitly invoked by its class’s destructor (~Vector_container()).

关于 #1,为什么覆盖发生在不同名称的函数中?

关于 #2,类的析构函数系统地调用成员析构函数是否是 C++ 的一个特性?

最佳答案

如果您不添加析构函数,编译器会创建一个析构函数。在你的情况下你有一个,所以编译器不会生成一个。

是的,成员和基类在类的析构函数被调用后被析构。来自 cppreference.com :

For both user-defined or implicitly-defined destructors, after the body of the destructor is executed, the compiler calls the destructors for all non-static non-variant members of the class, in reverse order of declaration, then it calls the destructors of all direct non-virtual base classes in reverse order of construction (which in turn call the destructors of their members and their base classes, etc), and then, if this object is of most-derived class, it calls the destructors of all virtual bases.

关于c++ - 了解 C++ 析构函数在派生类中的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56969615/

相关文章:

c++ - 是否可以在运行时确定指针指向 C++ 类还是指向 Objective-C 类?

c++ - Qt Creator - 无法将信号连接到插槽(没有匹配的调用功能)

c++ - 数组声明为 unsigned char 时的垃圾值

C++ Mixin - 初始化期间的动态绑定(bind)习语

java - 什么时候使用 super()?

c++ - 将 unsigned char 字符串从 native 客户端模块发送到浏览器

java - 为什么继承在 Java 和 C++ 中的行为不同,父类(super class)调用(或不调用)子类的方法?

c++ - 为什么这个使用构造函数和析构函数的 C++ 程序显示错误?

c++ - 为什么不在 C++ 中调用析构函数?

c++ - 原始类型动态分配数组的析构函数?