1 #define _CRT_SECURE_NO_WARNINGS 2 #include <iostream> 3 #include <cstring> 4 using namespace std; 5 6 //默认拷贝构造只是值传递,对于数据有效,对于指针则是同一个指向,需要重写一下拷贝构造 7 //类的内部有指针分配内存,需要深拷贝,否则需要浅拷贝 8 class mystring 9 { 10 public: 11 char *pstr; 12 int length; 13 14 public: 15 mystring(char *str) 16 { 17 this->length = strlen(str) + 1; 18 this->pstr = new char[this->length]{ 0 }; 19 strcpy(this->pstr, str);//初始化 20 } 21 22 //拷贝构造 23 mystring(const mystring &mystr) 24 { 25 this->length = mystr.length; 26 this->pstr = new char[this->length]{ 0 }; 27 strcpy(this->pstr, mystr.pstr); 28 } 29 30 31 void show() 32 { 33 cout << length << " " << (void *)pstr << " " << endl; 34 } 35 }; 36 37 38 void main() 39 { 40 mystring str1("gogogo"); 41 str1.show(); 42 //浅拷贝指向的地址都一样 43 mystring str2(str1); 44 str2.show(); 45 cin.get(); 46 }