【发布时间】:2018-01-12 13:16:10
【问题描述】:
我为它创建了一个派生类对象和一个基类点, 然后我使用 dynamic_cast 将基类点转换为派生类点。 我删除了派生类点,但程序调用了派生析构函数和基析构函数。为什么程序调用基本析构函数?毕竟,基本析构函数不是虚函数......
#include<iostream>
#include<stdlib.h>
using namespace std;
class con {
private:
double num;
public:
con() {
num = 0;
cout << "default..." << endl;
}
void getnum() {
cout << num << endl;
}
};
class base {
public:
virtual void A() {
cout << "it is base A" << endl;
}
void B() {
cout << "it is base B" << endl;
}
~base() {
cout << "it is base decon" << endl;
}
};
class child : public base {
public:
void A() {
cout << "it is child A" << endl;
}
void B() {
cout << "it is child B" << endl;
}
~child() {
cout << "it is child decon" << endl;
}
};
int main(int argc, char** argv) {
base* b = new child();
child* c = dynamic_cast<child*>(b);
delete c; //the program print "it is child decon" "it is base decon"
getchar();
return 0;
}
【问题讨论】:
-
你真的应该把析构函数变成虚拟的!
-
如果你总是删除具体类型,你就不需要虚拟析构函数。但正如@Someprogrammerdude 所说:不要这样做。
-
我不知道为什么程序调用派生析构函数然后调用基类析构函数,即使我没有将基类析构函数设为虚拟......我原以为它应该只调用派生的析构函数。谢谢...:-)@manni66
-
啊。现在我明白了。派生类总是调用派生析构函数和基类析构函数。谢谢@manni66