97.重载类的+法与深拷贝构造(拷贝构造深拷贝,赋值深拷贝)
1 #define _CRT_SECURE_NO_WARNINGS 2 #include <iostream> 3 #include <locale.h> 4 using namespace std; 5 6 //返回值为类的引用不会调用拷贝构造 7 //拷贝构造要深拷贝,赋值重载(=)也要深拷贝 8 //注意对象如果是在栈上,有生命周期,拷贝栈上的对象需要深拷贝 9 10 class mystring 11 { 12 public: 13 char *p; 14 int n; 15 16 public: 17 mystring() : p(nullptr), n(0) 18 { 19 20 } 21 mystring(char *str) 22 { 23 p = new char[strlen(str) + 1]; 24 n = strlen(str) + 1; 25 strcpy(p, str); 26 } 27 28 mystring(const mystring &my) 29 { 30 n = my.n; 31 p = new char[n]; 32 strcpy(p, my.p); 33 } 34 35 ~mystring() 36 { 37 delete p; 38 } 39 40 //void operator +(mystring &str) 41 //{ 42 // this->n += strlen(str.p); 43 // //分配内存 44 // char *ptemp = new char[this->n]; 45 // //拷贝 46 // strcpy(ptemp, this->p); 47 // strcat(ptemp, str.p); 48 // delete this->p; 49 // this->p = ptemp; 50 //} 51 52 //返回一个对象 53 //mystring operator +(mystring &str) 54 //{ 55 // this->n += strlen(str.p); 56 // //分配内存 57 // char *ptemp = new char[this->n]; 58 // //拷贝 59 // strcpy(ptemp, this->p); 60 // strcat(ptemp, str.p); 61 // delete this->p; 62 // this->p = ptemp; 63 64 // return (*this); 65 //} 66 67 //如果返回的是引用则不会调用拷贝构造 68 mystring &operator +(mystring &str) 69 { 70 this->n += strlen(str.p); 71 //分配内存 72 char *ptemp = new char[this->n]; 73 //拷贝 74 strcpy(ptemp, this->p); 75 strcat(ptemp, str.p); 76 delete this->p; 77 this->p = ptemp; 78 79 return (*this); 80 } 81 }; 82 83 void main() 84 { 85 mystring *my1 = new mystring("hello"); 86 mystring *my2 = new mystring("world"); 87 mystring my3 = *my1 + *my2; 88 delete my1; 89 cout << my3.p << endl; 90 cin.get(); 91 }