C++编译器至少给一个类添加4个函数
    默认构造函数(无参,函数体为空)
    默认析构函数(无参,函数体为空)
    默认拷贝构造函数,对属性进行值拷贝(形参:const 类名 &obj)
    赋值运算符operator=,对属性进行值拷贝

    如果类中有属性指向堆区,做赋值操作时也会出现深浅拷贝问题

    1. //赋值运算符重载
    2. class Person
    3. {
    4. public:
    5. Person(int age)
    6. {
    7. m_age = new int(age);
    8. }
    9. //重载 赋值运算符
    10. Person &operator=(Person& p)
    11. {
    12. //编译器提供的拷贝操作
    13. //m_age = p.m_age;
    14. //应该先判断是否有属性在堆区,如果有先释放干净,然后再深拷贝
    15. if (m_age != nullptr)
    16. {
    17. delete m_age;
    18. m_age = nullptr;
    19. }
    20. //深拷贝
    21. m_age = new int(*p.m_age);
    22. return *this;
    23. }
    24. ~Person()
    25. {
    26. if (m_age != nullptr)
    27. {
    28. delete m_age;
    29. m_age = nullptr;
    30. }
    31. }
    32. int* m_age;
    33. };
    34. void test01()
    35. {
    36. Person p1(18);
    37. Person p2(20);
    38. Person p3(30);
    39. p3 = p2 = p1;
    40. cout << "P1的年龄是:" << *p1.m_age << endl;
    41. cout << "P2的年龄是:" << *p2.m_age << endl;
    42. cout << "P3的年龄是:" << *p3.m_age << endl;
    43. }
    44. int main()
    45. {
    46. test01();
    47. int a = 10;
    48. int b = 20;
    49. int c = 30;
    50. c = b = a;
    51. cout << "a = " << a << endl;
    52. cout << "b = " << b << endl;
    53. cout << "c = " << c << endl;
    54. system("pause");
    55. return 0;
    56. }