浅拷贝和深拷贝

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 
 4 class person
 5 {
 6 public:
 7 
 8     person(int age,int height)
 9     {
10         m_age = age;
11         m_Height = new int(height);//我们在堆区开辟了内存,我们需要在某个时候释放 
12         puts("有参构造函数调用");
13     }
14 
15     person(const person &p)
16     {
17         puts("拷贝构造函数调用");
18         m_age = p.m_age;
19         m_Height = new int(*p.m_Height);
20     }
21     ~person()
22     {
23         if(m_Height != NULL)
24         {
25             delete m_Height;
26             m_Height = NULL;
27         } 
28         puts("析构函数调用");
29     }
30 
31     int m_age;
32     int *m_Height;
33 };
34 
35 
36 void test01()
37 {
38     person p(22,160);
39     cout << p.m_age << " " << *p.m_Height << endl;
40     person p2(p);
41     cout << p2.m_age << " " << *p2.m_Height << endl;
42 } 
43 
44 int main()
45 {
46     //test();
47     test01();
48     return 0;
49 }
View Code

分别是浅拷贝和深拷贝的示意图

原文地址:https://www.cnblogs.com/mch5201314/p/11602852.html