我正在阅读 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(); }
};
作者接着说
- The destructor (
~Vector_container()
) overrides the base class destructor (~Container()
).- 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/