这一篇文章使用操作符重载实现 auto_ptr 类。如果您没有使用过此类,请先查阅相关资料。
#include <iostream>
using namespace std;
class A
{
public:
~A()
{
cout << "销毁A" << endl;
}
void Show()
{
cout << "我是类A" << endl;
}
};
template<typename T>
class AutoPtr
{
T* pt;
public:
AutoPtr(T* ptr) : pt(ptr){}
~AutoPtr()
{
delete pt;
}
T* operator->()
{
return pt;
}
T& operator*()
{
return *pt;
}
};
int main(){
AutoPtr<A> autoPtr(new A());
autoPtr->Show();
(*autoPtr).Show();
return 0;
}
实现的auto_ptr并不完善,仅作为学习操作符重载的样例。