// ============================================================================ // p1c04_03_10 — 4.3.9.4 delete operator // 来源:川大 C++/LinuxC wiki「02.Qt方向」 // 说明:本文件由 gen_part1.py 合并页面中的教学片段而成。每个片段用 // // --- 原文片段 [pageId:blockIdx] --- 标注出处。 // 已做最小修正(笔误/平台移植),详见 docs/ERRATA.md。 // ============================================================================ #include using namespace std; #include // --- 原文片段 [58954451:9] 4.3.9.4 delete operator --- class Person{ public: Person(){ cout << "无参构造函数!" << endl; pName = (char*)malloc(strlen("undefined") + 1); strcpy(pName, "undefined"); mAge = 0; } Person(char* name, int age){ cout << "有参构造函数!" << endl; pName = (char*)malloc(strlen(name) + 1); strcpy(pName, name); mAge = age; } void ShowPerson(){ cout << "Name:" << pName << " Age:" << mAge << endl; } ~Person(){ cout << "析构函数!" << endl; if (pName != NULL){ delete pName; pName = NULL; } } public: char* pName; int mAge; }; void test(){ Person* person1 = new Person; Person* person2 = new Person("John",33); person1->ShowPerson(); person2->ShowPerson(); delete person1; delete person2; } // --- main --- int main() { test(); return 0; }