智能指針其實就是對->和*運算符重載的應用
#include <iostream>
#include <cstring>
using namespace std;
class Person{
public:
Person(int age){
cout << "有參構造函數調用" << endl;
this->m_age = age;
}
void showAge(){
cout << "年齡:" << this->m_age << endl;
}
~Person(){
cout << "析構函數調用" << endl;
}
private:
int m_age;
};
//智能指針 用來託管new出來的對象的釋放
class SmartPointer{
public:
SmartPointer(Person* person){
cout << "SmartPointer" << endl;
this->person = person;
}
//重載指針運算符
Person* operator->(){
return this->person;
}
//重載*運算符
Person& operator*(){
return *this->person;
}
~SmartPointer(){
if(this->person != NULL){
cout << "~SmartPointer" << endl;
delete this->person;
this->person = NULL;
}
}
private:
Person* person;
};
void test01(void){
// Person* p = new Person(18);
// delete p;
SmartPointer sp = SmartPointer(new Person(18));
sp->showAge(); //sp->->showAge(),編譯器簡化爲sp->showAge()
(*sp).showAge();
}
int main(int argc, char* argv[]){
test01();
system("pause");
return 0;
}