1 #include <cstring>
2 #include <iostream> // 标准的输入输出
3 using namespace std;
4
5 class Person {
6 public:
7 // 系统默认提供构造函数、拷贝构造、析构函数、赋值运算符
8 Person(int a)
9 {
10 ¦ this->m_A = a;
11 }
12 int m_A;
13 };
14
15 void test01()
16 {
17 Person p1(10);
18 Person p2(20);
19 p2 = p1;
20 cout << p2.m_A << endl;
21 }
22
23 class Person2 {
24 public:
25 Person2(const char* name)
26 {
27 ¦ this->m_Name = new char[strlen(name) + 1];
28 ¦ strcpy(this->m_Name, name);
29 }
30 char* m_Name;
31
32 Person2& operator=(Person2& p)
33 {
34 ¦ if (this->m_Name != NULL) {
35 ¦ ¦ delete[] this->m_Name;
36 ¦ ¦ this->m_Name = NULL;
37 ¦ }
38 ¦ this->m_Name = new char[strlen(p.m_Name) + 1];
39 ¦ strcpy(this->m_Name, p.m_Name);
40 ¦ return *this;
41 }
42 ~Person2()
43 {
44 ¦ if (this->m_Name != NULL) {
45 ¦ ¦ delete this->m_Name;
46 ¦ ¦ this->m_Name = NULL;
47 ¦ }
48 }
49 };
50
51 void test02()
52 {
53 Person2 p3("zhangsan");
54 Person2 p4("lisi");
55 // 简单的值传递会引起深浅拷贝问题,需要对赋值运算符重载
56 p4 = p3;
57 cout << p4.m_Name << endl;
58 }
59
60 int main()
61 {
62 test01();
63 test02();
64 return 0;
65 }
c++ 赋值运算符的重载
最新推荐文章于 2024-04-25 18:40:56 发布