// ============================================================================ // p1c04_06_03 — 4.6.5 指针运算符(*、->)重载 // 来源:川大 C++/LinuxC wiki「02.Qt方向」 // 说明:本文件由 gen_part1.py 合并页面中的教学片段而成。每个片段用 // // --- 原文片段 [pageId:blockIdx] --- 标注出处。 // 已做最小修正(笔误/平台移植),详见 docs/ERRATA.md。 // ============================================================================ #include using namespace std; // --- 原文片段 [58954458:2] 4.6.5 指针运算符(*、->)重载 --- class Person{ public: Person(int param){ this->mParam = param; } void PrintPerson(){ cout << "Param:" << mParam << endl; } private: int mParam; }; class SmartPointer{ public: SmartPointer(Person* person){ this->pPerson = person; } //重载指针的->、*操作符 Person* operator->(){ return pPerson; } Person& operator*(){ return *pPerson; } ~SmartPointer(){ if (pPerson != NULL){ delete pPerson; } } public: Person* pPerson; }; void test01(){ //Person* person = new Person(100); //如果忘记释放,那么就会造成内存泄漏 SmartPointer pointer(new Person(100)); pointer->PrintPerson(); } // --- main --- int main() { test01(); return 0; }