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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值