我正在使用 GNU 编译器。B 类中的虚拟析构函数不调用析构函数 ~D()。谁能告诉我为什么?
#include<iostream>
using namespace std;
class B {
double* pd;
public:
B() {
pd=new double [20];
cout<< "20 doubles allocated\n";
}
virtual ~B() { //the virtual destructor is not calling ~D()
delete[] pd;
cout<<"20 doubles deleted\n";
}
};
class D: public B {
int* pi;
public:
D():B() {
pi= new int [1000];
cout<< "1000 ints allocated\n";
}
~D() {
delete[] pi;
cout< "1000 ints deleted\n";
}
};
int main() {
B* p= new D; //new constructs a D object
Delete 应该调用 B 类中的虚拟析构函数,但它没有。
delete p;
}