#include <iostream>
using namespace std;
class Pointer
{
public:
Pointer();
Pointer(int _x, int _y);
Pointer(const Pointer &other);
void show();
int *x;
int *y;
};
Pointer::Pointer() : x(new int(-1)),y(new int(-1))
{
cout << "默认构造函数" << endl;
}
Pointer::Pointer(int _x,int _y) : x(new int(_x)),y(new int (_y))
{
cout << "构造函数" <<endl;
}
Pointer::Pointer(const Pointer &other) : x(new int(*(other.x))),y(new int (*(other.y)))//深拷贝,浅拷贝只传指针的指向,new的话是在堆区新建了存储区域
{//如果是浅拷贝只会单纯的改变值,如果一个值发生改变,另外一个值也会发生改变
cout << "拷贝构造函数" << endl;
}
void Pointer::show()
{
cout << "x = " << *x << "y = " << *y <<endl;
}
int main(int argc, const char *argv[])
{
Pointer p;
p.show();
Pointer p1(10,10);
p1.show();
Pointer p2(p1);
p2.show();
delete p.x;
delete p1.x;//如果只是浅拷贝的话会出现bug,p1.x与p2.x会出现双重delete
delete p2.x;
delete p.y;
delete p1.y;
delete p2.y;
p.x = NULL;
p1.x = NULL;
p2.x = NULL;
p.y = NULL;
p1.y = NULL;
p2.y = NULL;
return 0;
}
深拷贝和浅拷贝只是针对成员变量而言的,两个对象的数据成员指向同一片区域就是浅拷贝,而不指向(new)的话就是深拷贝