提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
一、智能指针
最近在学习C++的过程中简单编写了一个智能指针,以供参考。
二、使用步骤
1.代码
代码如下:
#include <iostream>
#include <string>
using namespace std;
template <typename T>
class MyPtr
{
private:
T * p;
public:
MyPtr(T * p);
~MyPtr();
void Show() { cout << "地址为" << p << " 值为" << *p << endl; }
T & operator*();
};
template <typename T>
MyPtr<T>::MyPtr(T * p)
{
this->p = p;
cout << "创建。地址为:" << p << endl;
}
template <typename T>
T & MyPtr<T>::operator*()
{
return *(this->p);
}
template <typename T>
MyPtr<T>::~MyPtr()
{
delete p;
cout << "删除。地址为:" << p << " 值为:" << *p << endl;
}
int main(void)
{
{
MyPtr<double> mp(new double);
*mp = 25.5;
mp.Show();
}
return 0;
}