赋值运算符重载(4)

C++编译器至少给一个类添加4个函数

1.默认构造函数(无参,函数体为空)

2.默认析构函数(无参,函数体为空)

3.默认拷贝构造函数,对属性进行值拷贝

4.赋值运算符operator=,对属性进行值拷贝

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

 1 #include <iostream>
 2 using namespace std;
 3 
 4 //赋值运算符重载
 5 class Person
 6 {
 7 public:
 8     Person(int age)
 9     {
10         m_Age = new int(age);
11     }
12 
13     ~Person()
14     {
15         if (m_Age != NULL)
16         {
17             delete m_Age;
18             m_Age = NULL;
19         }
20     }
21 
22     //重载赋值运算符
23     Person& operator=(Person &p)
24     {
25         //编译器提供浅拷贝
26         //m_Age = p.m_Age
27 
28         //应该先判断是否有属性在堆区,如果有先释放干净
29         if (m_Age != NULL)
30         {
31             delete m_Age;
32             m_Age = NULL;
33         }
34 
35         //深拷贝操作
36         m_Age = new int(*p.m_Age);
37 
38         //返回自身,实现连等,p3 = p2 = p1 赋值操作
39         return *this;
40     }
41 
42     int *m_Age;
43 };
44 
45 void test_01(void)
46 {
47     Person p1(18);
48 
49     Person p2(20);
50 
51     Person p3(30);
52 
53     p3 = p2 = p1;//赋值操作,开始挖坑了,因为数据开辟在堆区,赋值之后会带来浅拷贝问题
54 
55     cout << "p1的年龄:" << *p1.m_Age << endl;
56 
57     cout << "p2的年龄:" << *p2.m_Age << endl;
58 }
59 
60 int main(void)
61 {
62     test_01();
63 
64     system("pause");
65     return 0;
66 }

 

posted @ 2020-04-26 14:32  坦率  阅读(152)  评论(0)    收藏  举报