实现自动delete?
main.cpp
#include <iostream>
#include"person.h"
using namespace std;
int main()
{
Person* p = new Person(100);
p->printPerson();
smartPointer sp(new Person(200));
sp.mp->printPerson();
sp->printPerson();
//delete p;
//加入用户忘记delete p
cout << "Hello World!" << endl;
return 0;
}
Person.h
#ifndef PERSON_H
#define PERSON_H
#include<iostream>
using namespace std;
class Person
{
private:
int num;
public:
Person();
Person(int num)
{
this->num =num;
}
~Person()
{
cout<<"xigou"<<endl;
}
public:
void printPerson(void)
{
cout<<"num= "<<num<<endl;
}
};
class smartPointer
{
public:
Person* mp;
public:
smartPointer(Person* p)
{
mp = p;
}
~smartPointer()
{
if(mp != NULL)
{
cout<<"smartxigou"<<endl;
delete mp;
}
}
Person* operator->()
{
return mp;
}
Person operator*()
{
return *mp;
}
};
#endif // PERSON_H