89.赋值重载以及深浅拷贝

  • 非指针,则深浅拷贝都一样,含有指针则内存共享,指针一致,内容一直
  • 深拷贝,指针不一致,内存一直,内存是独享的
  • 赋值重载如果有返回自身类型对象,会调用拷贝构造,需要重载拷贝构造,这一点是必须要注意的,原理是:先操作一个类,再把操作的这个类拷贝到本类中,即使返回(*this),也会调用 (如果返回值是自身类型,赋值重载的this指针是不是本类的this指针!!!!所以需要拷贝构造)

代码示例:

 1 #define _CRT_SECURE_NO_WARNINGS
 2 #include <iostream>
 3 using namespace std;
 4 
 5 //非指针,则深浅拷贝都一样,含有指针则内存共享,指针一致,内容一直
 6 //深拷贝,指针不一致,内存一直,内存是独享的
 7 //赋值重载如果有返回自身类型对象,会调用拷贝构造
 8 //原理是:先操作一个类,再把操作的这个类拷贝到本类中,即使返回(*this),也会调用
 9 
10 class mystring
11 {
12 public:
13     char *p;
14     int n;
15     mystring() :p(nullptr), n(0)
16     {
17 
18     }
19 
20     mystring(char *str)
21     {
22         cout << "构造函数调用" << endl;
23         n = strlen(str) + 1;
24         p = new char[n];
25         strcpy(this->p, str);//拷贝
26     }
27 
28     mystring(const mystring &my)
29     {
30         cout << "拷贝构造函数调用" << endl;
31         cout << (void *)p << endl;
32         this->n = my.n;
33         this->p = new char[this->n];
34         strcpy(this->p, my.p);//拷贝
35     }
36 
37     ////重载=
38     //void operator =(const mystring &stringmy)
39     //{
40     //    delete this->p;
41     //    cout << "赋值重载调用" << endl;
42     //    this->n = stringmy.n;
43     //    this->p = new char[this->n];
44     //    strcpy(this->p, stringmy.p);
45     //}
46 
47     //使可以多次重载
48     mystring operator =(const mystring &stringmy)
49     {
50         cout << "赋值重载调用" << endl;
51         delete this->p;
52         this->n = stringmy.n;
53         this->p = new char[this->n];
54         cout << (void *)p << endl;
55         strcpy(this->p, stringmy.p);
56         return (*this);
57     }
58 
59     ~mystring()
60     {
61         delete this->p;
62     }
63 };
64 
65 void main()
66 {
67     mystring my1("12345");
68     mystring my2,my3;
69     //赋值重载
70     my3 = my2 = my1;
71     cout << my3.p << endl;
72     cin.get();
73 }
原文地址:https://www.cnblogs.com/xiaochi/p/8596814.html