智能指针
使用智能指针来托管自定义类型的对象,让对象进行自动的释放。
#include<iostream>
using namespace std;
class Person{
public:
Person(int age){
this->age = age;
}
int age;
void show_age(){
cout<<"nianling is "<<this->age;
}
~Person(){
cout<<"diaoyongxigou"<<endl;
}
};
class smartPointer{
public:
smartPointer(Person *p){
this ->person = p;
}
Person* operator->(){
return this->person;
}
Person& operator*(){
return *(this->person);
}
~smartPointer(){
cout<<"zhi neng zhi zhen xi gou"<<endl;
if(this->person !=NULL){
delete this->person;
this->person = NULL;
}
}
private:
Person *person;
};
void test_01(){
smartPointer sp (new Person(10));
sp->show_age();
(*sp).show_age();
}
int main(){
test_01();
system("pause");
}
|