31:这几题都是举例使用动态内存管理类,多是代码,多写写
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
class Hasptr1
{
friend void swap(Hasptr1&,Hasptr1&);
friend bool operator<(const Hasptr1& s1,const Hasptr1& s2);
friend void show(vector<Hasptr1>& vec);
public:
//构造函数,初始化相关成员
Hasptr1(const string& s = string()):ps(new string(s)),i(0),use(new size_t(1)){}
//拷贝构造函数,将引用计数也拷贝过来,并且递增引用计数
Hasptr1(const Hasptr1& p):ps(p.ps),i(p.i),use(p.use){++*use;}
//拷贝赋值运算符
Hasptr1& operator= (const Hasptr1& p1)
{
++*p1.use;//首先递增右侧运算符对象的引用计数
if (--*use == 0)//递减本对象的引用计数,若没有其他用户,则释放本对象的成员
{
delete ps;
delete use;
}
ps