浅层复制:
- 实现对象间数据元素的一一对应复制
深层复制:
- 当被复制的对象数据成员是指针类型时,不是复制该指针成员本身,而是将指针所指对象进行复制
对象的浅层复制:
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;
}
正确