【注意】
#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; }