嘿,为什么在这个程序结束时调用了两次基本析构函数?
#include <iostream>
using namespace std;
class B{
public:
B(){
cout << "BC" << endl; x = 0;
}
virtual ~B(){
cout << "BD" << endl;
}
void f(){
cout << "BF" << endl;
}
virtual void g(){
cout << "BG" << endl;
}
private:
int x;
};
class D: public B{
public:
D(){
cout << "dc" << endl; y = 0;
}
virtual ~D(){
cout << "dd" << endl;
}
void f(){
cout << "df" << endl;
}
virtual void g(){
cout << "dg" << endl;
}
private:
int y;
};
int main(){
B b, * bp = &b;
D d, * dp = &d;
bp->f();
bp->g();
bp = dp;
bp->f();
bp->g();
}
最佳答案
析构函数按顺序调用,就像它们展开相应构造函数的效果一样。因此,首先是派生对象的析构函数,然后是基础对象的析构函数。将析构函数设为虚拟对调用/不调用基类析构函数没有任何影响。
还要提一下,您的示例可以这样简化(此代码还会导致调用基析构函数两次和派生析构函数一次):
struct A {
~A() {
// ...
}
};
struct B: A {
~B() {
// ...
}
};
int main() {
A a;
B b;
}
关于c++ - 在派生对象之后调用两次基本析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2980386/