c++编译器会给类添加2个函数:
默认拷贝构造函数,对属性进行值拷贝。
赋值运算符operator=,对属性进行值拷贝。
默认拷贝构造函数可以实现对象的拷贝,如point p1(p2);
而赋值运算符函数可以实现对象的赋值,如p1=p2。
但对于浅拷贝(系统给的)来说,如果两个对象的成员变量是在堆中申请的空间,在拷贝和赋值的时候都会将地址拷贝或赋值给另一个对象,导致释放这2个对象中的堆空间时造成多次对同一块堆空间释放,要解决这一问题我们需要深拷贝来解决。
利用自定义拷贝构造函数实现深拷贝:#include <iostream>
using namespace std;
class point
{
public:
int x;
int *y;
point()
{
x=0;
y=new int(0);
}
point(int x,int y)
{
this->x=x;
this->y=new int(y);
}
~point()
{
delete y;
}
//深拷贝构造函数
point(const point &p1)
{
this->x=p1.x;
this->y=new int(*p1.y);
}
};
int main()
{
point p1(2,2);
point p2(p1);
cout<<p2.x;
return 0;
}
利用自定义赋值运算符函数重载实现:
#include <iostream>
using namespace std;
class point
{
public:
int x;
int *y;
point()
{
x=0;
y=new int(0);
}
point(int x,int y)
{
this->x=x;
this->y=new int(y);
}
~point()
{
delete y;
}
void operator=(point &p1)
{
this->x=p1.x;
this->y=new int(*p1.y);
}
};
int main()
{
point p1(2,2),p2;
p2=p1;
cout<<p2.x;
return 0;
}