#include<iostream>
using namespace std;
class Father {
public:
Father(const char * Name="中国") {
int len = strlen(Name)+1;
this->Name = new char[len];
strcpy_s(this->Name, len, Name);
cout << "调用父类构造函数" << endl;
}
~Father() {
if (Name) {
delete Name;
Name = NULL;
cout << "调用父类析构函数" << endl;
}
}
private:
char* Name;
};
class Son :public Father {
public:
Son (const char* Game = "游戏") {
int len = strlen(Game)+1;
this->Game = new char[len];
strcpy_s(this->Game, len, Game);
cout << "调用子类构造函数" << endl;
}
~Son() {
if (Game) {
delete Game;
Game = NULL;
cout << "调用子类析构函数" << endl;
}
}
private:
char* Game;
};
int main()
{
cout << "**************case 1:***************" << endl;
Father *father=new Father();
delete father;
cout << "**************case 2:***************" << endl;
Son* son = new Son();
delete son;
cout << "**************case 3:***************" << endl;
Father* f = new Son();
delete f;
return 0;
}
结果如下:
可以看见case3并没有调用子类析构函数
会导致子类中的内存没法释放而导致泄露
原因:
C++特性 在用子类给父类对象实例化的时候会导致析构的时候只调用父类的析构函数
解决方案:
virtual ~Father() {
if (Name) {
delete Name;
Name = NULL;
cout << "调用父类析构函数" << endl;
}
}
在父类前面加上virtual即可 而且注意保持好习惯 需要作为基类的函数最好加上virtual