重载赋值运算符2

#include <iostream>
#include <string>

using namespace std;

class Dog
{
private:
	string nm;
public: 
	Dog(const string& name) : nm(name)
	{
		cout << "Creating Dog: " << *this << endl;
	}
	~Dog()
	{
		cout << "Deleting Dog: " << *this << endl;
	}
	Dog(const Dog* dp, const string& msg) : nm(dp->nm + msg)
	{
		cout << "Creating Dog: " << *this << " from " << *dp << endl;
	}
	void rename(const string& newName)
	{
		nm = newName;
		cout << "Dog renamed to: " << *this << endl;
	}

	friend ostream& operator<<(ostream& os, const Dog& d)
	{
		return os << "[" << d.nm << "]";
	}
};

class DogHouse
{
private:
	Dog* p;
	string houseName;
public:
	DogHouse(Dog* dog, const string& house) :p(dog), houseName(house)
	{

	}
	DogHouse(const DogHouse& dh) :p(new Dog(dh.p, " copy-constructed")), houseName(dh.houseName + " copy-constructed")
	{

	} // 这个就是深复制,创建了一个新的(Dog)指针,
	DogHouse& operator=(const DogHouse& dh)
	{
		if (&dh != this)
		{
			p = new Dog(dh.p, " assigned");
			houseName = dh.houseName + " assigned";
		}
		return *this;
	}
	~DogHouse()
	{
		delete p;
		cout << "析构函数, " << endl;
	}
	Dog* getDog() const
	{
		return p;
	}
	void rename(const string& newName)
	{
		houseName = newName;
	}

	friend ostream& operator<<(ostream& os, const DogHouse& dh)
	{
		return os << "[" << dh.houseName << "] constains " << *dh.p;
	}
};

int main()
{
	DogHouse d1(new Dog("Fee"), "FeeHouse");
	cout << d1 << endl << endl;

	d1.getDog()->rename("Fee2");
	cout << d1 << endl << endl;

	d1.rename("Fee2House");
	cout << d1 << endl << endl;

	//DogHouse d2 = d1;  // 调用复制构造函数,
	//d2.getDog()->rename("Tree");
	//d2.rename("TreeHouse");  // C++默认的就是浅复制,
	//cout << d1 << endl;  // 这里只是浅复制,在更改后TreeHouse不相同,但是rename是相同的,
	//cout << d2 << endl << endl;

	DogHouse d2 = d1;  
	d2.getDog()->rename("Tree");
	d2.rename("TreeHouse");  
	cout << d1 << endl;  
	cout << d2 << endl << endl;

	//DogHouse d2 = d1;
	//d1 = d2;  // 调用重载构造函数,
	cout << "hello" << endl;
	d1 = d2;
	cout << d1 << endl;
	cout << d2 << endl;
	cout << "xiu gai hou ," << endl;
	d1.getDog()->rename("xiao cui");
	d1.rename("xiao cui house");
	cout << d1 << endl;
	cout << d2 << endl;
	// 当用到了指针的时候才使用深复制,没有用到指针就不分浅复制和深复制,

	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值