子类的析构函数
【注意】
- 为了防止内存泄露,最好是在基类析构函数上添加virtual关键字,使基类析构函数为虚函数
- 目的在于,当使用delete释放基类指针时,会实现动态的析构:
- 如果基类指针指向的是基类对象,那么只调用基类的析构函数
- 如果基类指针指向的是子类对象,那么先调用子类的析构函数,再调用父类的析构函数
#include <iostream>
#include <Windows.h>
using namespace std;
class Father {
public:
Father(const char* name = "无名") {
cout << "调用Father构造函数" << endl;
this->name = new char[strlen(name) + 1];
strcpy_s(this->name, strlen(name) + 1, name);
}
virtual ~Father() {
if (name) {
cout << "调用Father析构函数" << endl;
delete[] name;
name = NULL;
}
}
private:
char* name;
};
class Son : public Father {
public:
Son(const char* game = "篮球", const char* name = "无名") :Father(name) {
cout << "调用Son构造函数" << endl;
this->game = new char[strlen(game) + 1];
strcpy_s(this->game, strlen(game) + 1, game);
}
~Son(){
if (game) {
cout << "调用Son析构函数" << endl;
delete[] game;
game = NULL;
}
}
private:
char* game;
};
int main(void) {
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;
}