浅层复制和深层复制

浅层复制:

  • 实现对象间数据元素的一一对应复制

深层复制:

  • 当被复制的对象数据成员是指针类型时,不是复制该指针成员本身,而是将指针所指对象进行复制


对象的浅层复制:

class Point
{
	public:
		Point(): x(0), y(0) {}
		Point(int x, int y): x(x), y(y) {}
		int Getx()  {  return x;  }
		int Gety()  {  return y;  }
		void Move(int t, int q)  {  x += t, y += q;  }
	private:
		int x, y;
};
class Pts	//Point类的动态数组(封装成了类)
{
	public:
		Pts(int len): size(len)  {  s = new Point[size];  }
		~Pts()  {  delete[] s;  }
		Point &index(int id)  {  return s[id];  }
	private:
		Point *s;
		int size;
};
int main(void)
{
	int n;
	scanf("%d", &n);
	Pts a(n);
	a.index(0).Move(1, 1);
	a.index(1).Move(-1, -1);
	Pts b(a);
	printf("%d %d\n", b.index(0).Getx(), b.index(0).Gety());
	printf("%d %d\n", b.index(1).Getx(), b.index(1).Gety());
	a.index(0).Move(1, 1);
	a.index(1).Move(-1, -1);
	printf("%d %d\n", b.index(0).Getx(), b.index(0).Gety());
	printf("%d %d\n", b.index(1).Getx(), b.index(1).Gety());
	return 0;	//在这里会RE,因为复制动态数组时,只是将指针复制了,并没有多出来一个数组,从而析构时会对同一个内存析构两次导致出错
}


由上图可知,上面的程序会在最后析构时RE,因为复制动态数组时,只是将指针复制了,并没有多出来一个数组,从而析构时会对同一个内存析构两次导致出错


对象的深层复制:

#include <iostream>
#include <cassert>
using namespace std;
class Point
{
	public:
		Point(): x(0), y(0) {}
		Point(int x, int y): x(x), y(y) {}
		int Getx()  {  return x;  }
		int Gety()  {  return y;  }
		void Move(int t, int q)  {  x += t, y += q;  }
	private:
		int x, y;
};
class Pts	//Point类的动态数组(封装成了类)
{
	public:
		Pts(int len): size(len)  {  s = new Point[size];  }
		Pts(const Pts &b)		//手写复制函数,多申请一个数组,这也是和上面程序唯一的区别
		{
			int i;
			size = b.size;
			s = new Point[size];
			for(i=0;i<=size-1;i++)
				s[i] = b.s[i];
		}
		~Pts()  {  delete[] s;  }
		Point &index(int id)  {  return s[id];  }
	private:
		Point *s;
		int size;
};
int main(void)
{
	int n;
	scanf("%d", &n);
	Pts a(n);
	a.index(0).Move(1, 1);
	a.index(1).Move(-1, -1);
	Pts b(a);
	printf("%d %d\n", b.index(0).Getx(), b.index(0).Gety());
	printf("%d %d\n", b.index(1).Getx(), b.index(1).Gety());
	a.index(0).Move(1, 1);
	a.index(1).Move(-1, -1);
	printf("%d %d\n", b.index(0).Getx(), b.index(0).Gety());
	printf("%d %d\n", b.index(1).Getx(), b.index(1).Gety());
	return 0;
}

正确

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值