c++ primer 13.22练习(值行为的类)

13.22

#include <iostream>
#include <memory>
#include <string>
#include <vector>
using namespace std;

class HashPtr{
public:
	HashPtr(const string& s=string()) :ps(new string(s)), i(0) {}
	//定义值行为的拷贝构造函数
	HashPtr(const HashPtr& h) :ps(new string(*h.ps)), i(h.i) {}

	//定义值行为的赋值运算符
	HashPtr& operator= (const HashPtr&);
	HashPtr& operator= (const string&);

	//解引用运算符
	string& operator* ();

	//析构函数
	~HashPtr(){ delete ps; }
private:
	string *ps;
	int i;
};

inline
HashPtr& HashPtr::operator=(const HashPtr& h)
{
	auto newps = new string(*h.ps);//注意此处一定要先拷贝
	delete ps;//再销毁原string,注意顺序
	ps = newps;

	i = h.i;
	return *this;
}

inline
HashPtr& HashPtr::operator=(const string& s)
{
	auto newps = new string(s);
	delete ps;//销毁旧指针
	ps = newps;

	/*
	*习题册上给出的是*ps=s;return *this;这样的话ps指向的就是s,对*ps操作就是对s操作,不符合值行为
	*并且ps不再指向动态分配的内存单元了,这是不合适的。
	*/
	return *this;
}

inline
string& HashPtr::operator*()
{
	return *ps;
}

int main()
{
	HashPtr h("Hello world");//构造函数
	HashPtr h2(h);//拷贝构造函数
	HashPtr h3 = h;//赋值运算符

	cout << *h << endl;
	cout << *h2 << endl;
	cout << *h3 << endl;

	h2 = "Nihao";
	h3 = "Shijie";

	cout << *h << endl;
	cout << *h2 << endl;
	cout << *h3 << endl;

	system("pause");
	return 0; 
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章