1 //深拷贝与浅拷贝
2
3 //浅拷贝 : 简单的赋值拷贝操作
4 //深拷贝: 在堆区重新申请空间 进行拷贝操作
5
6
7 #include <iostream>
8 using namespace std;
9
10 class Person
11 {
12 public:
13 Person()
14 {
15 cout << "Person的默认构造函数调用" << endl;
16 }
17
18 Person(int age , int height)
19 {
20 m_Age = age;
21 m_Height = new int(height);
22 cout << "Person的有参构造函数调用" << endl;
23 }
24 //自己实现拷贝函数构造函数 解决浅拷贝带来的问题
25 Person(const Person &p)
26 {
27 cout << "Person 拷贝构造函数的调用" << endl;
28 m_Age = p.m_Age;
29 //m_Height = p.m_Height; //编译器默认实现就是这行代码
30 //深拷贝
31
32 m_Height = new int(*p.m_Height);
33
34 }
35 ~Person()
36 {
37 //析构代码,将堆区开辟数据做释放操作
38 if (m_Height != NULL)
39 {
40 delete m_Height;
41 m_Height = NULL;
42 }
43 cout << "Person的析构函数调用" << endl;
44 }
45
46
47 int m_Age;
48 int *m_Height;
49 };
50 void test01()
51 {
52 Person p1(18,160);
53 cout << "p1的年龄为: " << p1.m_Age <<" p1的身高为: " <<*p1.m_Height<< endl;
54
55 Person p2(p1); //我们没有写 拷贝构造函数 但是 编译器帮我们编译了 就是浅拷贝
56
57 cout << "p2的年龄为: " << p2.m_Age << " p1的身高为: " << *p2.m_Height<<endl;
58
59 }
60
61 int main()
62 {
63 test01();
64 }