C++:智能指针
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
Person(){};
Person(string name, int age)
{
this->name = name;
this->age = age;
};
void show()
{
cout<<"姓名:"<<this->name<<",年龄:"<<this->age<<endl;
}
private:
string name;
int age;
};
class SmartPointer
{
public:
SmartPointer(Person* p)
{
this->pointer = p;
};
// ->运算符重载
Person* operator->()
{
return this->pointer;
}
// *运算符重载
Person& operator*()
{
return *(this->pointer);
}
~SmartPointer()
{
if(NULL!=this->pointer)
{
delete this->pointer;
this->pointer = NULL;
}
}
private:
Person* pointer;
};
int main()
{
SmartPointer ps(new Person("刘备", 20));
ps->show();
(*ps).show();
return 0;
}