#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include"HasPtr.h"
//#include"TreeNode.h"
using namespace std;
//13.27 30 31编写自己版本的使用引用计数的HasPtr
int main(int argc, char *argv[])
{
//HasPtr p;
//p.Print();
//HasPtr p1 = p;
//p1.Print();
//p.Print();
//HasPtr p2(p);
//p.Print();
//p2.Print();
//HasPtr p3("my life");// 交换成功
//HasPtr p4("you life");
////cout<<p4.ps_str();
//Swap(p3, p4);
vector<HasPtr> vec_has;
string str;
while (cin >> str)
{
HasPtr temp1;
temp1.ps_str()=str;
cout<<temp1.ps_str();
vec_has.push_back(temp1);
}
stable_sort(vec_has.begin(), vec_has.end());
for (auto i : vec_has)
cout << i.ps_str() << " ";
system("pause");
}
下面的是这个文件:
#ifndef HasPtr_H
#define HasPtr_H
#include<string>
#include<iostream>
#include<vector>
using namespace std;
class HasPtr
{
friend void Swap(HasPtr &p, HasPtr &q);
friend bool operator<(const HasPtr &c, const HasPtr &d)
{
return *c.ps < *d.ps;
}
public:
//构造函数
HasPtr(const string &s=string()):ps(new string(s)),i(0),use(new size_t(1)){}
//拷贝构造函数
HasPtr(const HasPtr &p) :ps(p.ps), i(p.i), use(p.use) { ++*use; }
HasPtr &operator=(const HasPtr&) ;
string ps_str() { return (*ps); }
~HasPtr();
void Print();
private:
string *ps;
int i;
size_t *use;//用来记录有多少个对象共享use
};
HasPtr & HasPtr::operator=(const HasPtr &rhs)
{
++*rhs.use;
if (--*use == 0)
{
delete ps;
delete use;
}
ps = rhs.ps;//将数据rhs拷贝到本对象
i = rhs.i;
use = rhs.use;
return *this;
}
HasPtr::~HasPtr()
{
if (--*use == 0)
{
delete ps;
delete use;
}
}
void HasPtr::Print()
{
cout << *use << endl;
}
void Swap(HasPtr &p, HasPtr &q)
{
cout << *p.ps << *q.ps << endl;
HasPtr temp;
temp.ps = new string(*(p.ps));
temp.i = p.i;
delete p.ps;
p.ps = new string(*(q.ps));
p.i = q.i;
q = temp;
cout << *p.ps << *q.ps << endl;
}
#endif