5、深拷贝与浅拷贝.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. //4、2、5 深拷贝与浅拷贝
  2. //深拷贝是面试经典问题,也是常见的一个坑
  3. //浅拷贝:简单的复制拷贝操作
  4. //深拷贝:在堆区重新申请空间,进行拷贝操作
  5. //浅拷贝带来的问题就是堆区的内存重复释放
  6. //浅拷贝的问题要用深拷贝进行解决
  7. #if(0)
  8. #include <iostream>
  9. class Person
  10. {
  11. public:
  12. //无参默认构造函数
  13. Person()
  14. {
  15. std::cout << "Person的默认构造函数调用" << std::endl;
  16. }
  17. //有参构造函数
  18. Person(int age ,int height)
  19. {
  20. m_Age = age;
  21. m_Height = new int(height);
  22. std::cout << "Person的有参构造函数的调用" << std::endl;
  23. }
  24. //拷贝构造函数
  25. //自己实现拷贝函数 解决浅拷贝带来的问题
  26. Person(const Person& p)
  27. {
  28. std::cout << "Person拷贝构造函数的调用:" << std::endl;
  29. m_Age = p.m_Age;
  30. //m_Height = p.m_Height; 编译器默认实现就是这行代码
  31. //深拷贝操作
  32. m_Height = new int(*p.m_Height);
  33. }
  34. ~Person()
  35. {
  36. //析构代码的用途是将堆区开辟的代码数据做一个释放的操做
  37. if (m_Height != NULL)
  38. {
  39. delete m_Height;
  40. m_Height = NULL;
  41. }
  42. std::cout << "Person的析构函数的调用" << std::endl;
  43. }
  44. int m_Age; //年龄
  45. int* m_Height; //身高
  46. };
  47. void test01()
  48. {
  49. Person p1(18,160);
  50. std::cout << "P1的年龄为:" << p1.m_Age << "身高为:" << *p1.m_Height << std::endl;
  51. Person p2(p1);
  52. std::cout << "P2的年龄为:" << p2.m_Age << "身高为:" << *p2.m_Height << std::endl;
  53. }
  54. int main()
  55. {
  56. test01();
  57. system("pause");
  58. return 0;
  59. }
  60. //如果属性有在堆区开辟的,一定要自己提供拷贝构造函数,防止浅拷贝带来的问题
  61. #endif