#include <iostream>
using namespace std;
class Person
{
private:
int num;
public:
Person(int num):num(num)
{
//this->num = num;
cout<<"有參構造num = "<<num<<endl;
}
void showPerson(void)
{
cout<<"num = "<<num<<endl;
}
~Person()
{
cout<<"析構函數 num = "<<num<<endl;
}
};
//設計一個智能指針 解決 Person new出的堆區空間 釋放問題
class SmartPointer{
public:
Person *pPerson;
public:
SmartPointer(Person *p)
{
pPerson = p;
}
~SmartPointer()
{
if(pPerson != NULL)
{
delete pPerson;
pPerson = NULL;
}
}
//成員函數重載->運算符
Person* operator->()
{
return this->pPerson;
}
//成員函數 重載 *運算
Person& operator*()
{
return *(this->pPerson);
}
};
void test01()
{
Person *p = new Person(100);
p->showPerson();
//假如我忘了 delete p
//delete p;
//需求:自動的幫我釋放 堆區空間(智能指針的概念)
SmartPointer pointer(new Person(200));
//訪問Person類中的showPerson()
//pointer.pPerson->showPerson();
//保證指針的使用
//(pointer.operator ->())->showPerson();
pointer->showPerson();
(*pointer).showPerson();
}
int main(int argc, char *argv[])
{
test01();
return 0;
}
運行結果: