如果给定一个包含定义的析构函数的父类 A,B 的子类会在创建 B 对象时执行它吗?即使我没有手动创建也没有继承B类中A的析构函数?
自从我在 c++ 视频教程中看到它以来,我希望它会,但不明白为什么?因为Constructor是手动继承的!
最佳答案
编译器总是为你的类实现一个析构函数,如果你还没有声明的话。编译器还会生成调用基类析构函数的代码。
换句话说,基类析构函数不是继承的,而是在派生类析构函数之后调用的。
参见 Destructor :
Destruction sequence
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.
Even when the destructor is called directly (e.g. obj.~Foo();), the return statement in ~Foo() does not return control to the caller immediately: it calls all those member and base destructors first.
关于c++ - 如果不是手动完成,子类是否会继承父类的析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57391852/