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; 
}


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