一篇和正常的测试函数献上,并附上结果截图
可以看到最后少了Son的析构函数
解决的方法也很简单,在父类的析构函数前加上 virtual 就可以了
把father类的析构函数定义为virtual函数时
如果对 father 类的指针使用delete操作时
就会对该指针使用 “动态析构”
如果这个指针,指向的是子类对象
那么会先调用该子类的析构函数,再调用自己类的析构函数
------奇牛学院Rock老师
#include <iostream>
using namespace std;
class Father {
public:
Father(const char* addr = "中国") {
cout << "执行了father的构造函数" << endl;
int len = strlen(addr) + 1;
this->addr = new char[len];
strcpy_s(this->addr, len, addr);
};
~Father() {
cout<<"调用Father类析构函数"<<endl;
if (addr) {
delete addr;
addr = NULL;
}
};
private:
char* addr;
};
class Son :public Father {
public:
Son(const char* game = "游戏", const char* addr = "中国") :Father(addr){
cout << "执行了son的构造函数" << endl;
int len = strlen(game) + 1;
this->game = new char[len];
strcpy_s(this->game, len, game);
}
~Son() {
cout << "调用son的析构函数" << endl;
if (game) {
delete game;
game = NULL;
}
}
private:
char* game;
};
int main() {
cout << "----------------case1--------------" << endl;
Father* father = new Father();
delete father;
cout << "-------------case2---------------------" << endl;
Son* son = new Son();
delete son;
cout << "----------------case3-----------------------" << endl;
father = new Son();
delete father;
system("pause");
return 0;
}
加virtual后