浅拷贝:简单的赋值拷贝操作
    深拷贝:在堆区重新申请空间,进行拷贝操作

    1. //深拷贝与浅拷贝
    2. class Person
    3. {
    4. public:
    5. Person()
    6. {
    7. cout << "Person的默认构造函数调用" << endl;
    8. }
    9. Person(int age, int height)
    10. {
    11. m_Age = age;
    12. m_Height = new int(height);
    13. cout << "Person的有参构造函数调用" << endl;
    14. }
    15. //自己实现拷贝构造函数 解决浅拷贝带来的问题
    16. Person(const Person& p)
    17. {
    18. cout << "Person拷贝构造函数调用" << endl;
    19. m_Age = p.m_Age;
    20. //m_Height = p.m_Height; //浅拷贝操作;编译器默认实现的这行代码
    21. m_Height = new int(*p.m_Height); //深拷贝操作
    22. }
    23. ~Person()
    24. {
    25. //析构代码,将堆区开辟数据做释放操作
    26. if (m_Height != nullptr)
    27. {
    28. delete m_Height;
    29. m_Height = nullptr;
    30. }
    31. cout << "Person的析构函数调用" << endl;
    32. }
    33. int m_Age; //年龄
    34. int* m_Height; //身高
    35. };
    36. void test01()
    37. {
    38. Person p1(18, 160);
    39. cout << "P1的年龄为:" << p1.m_Age << "身高为:"<< *p1.m_Height << endl;
    40. Person p2(p1);
    41. cout << "P2的年龄为:" << p2.m_Age << "身高为:" << *p2.m_Height << endl;
    42. }
    43. int main()
    44. {
    45. test01();
    46. system("pause");
    47. return 0;
    48. }