标签:实现 浅拷贝 默认 name 问题 test out vat char
1 class Person 2 { 3 private: 4 char *m_name; 5 int m_num; 6 public: 7 Person() 8 { 9 m_name = NULL; 10 m_num = 0; 11 cout<<"无参构造"<<endl; 12 } 13 Person(char *name,int num) 14 { 15 //为m_name申请空间 16 m_name = (char *)calloc(1,strlen(name)+1); 17 if(m_name == NULL) 18 { 19 cout<<"构造失败"<<endl; 20 } 21 cout<<" 已经申请好空间"<<endl; 22 strcpy(m_name,name); 23 m_num = num; 24 cout<<"有参构造"<<endl; 25 } 26 27 Person(const Person &ob)//ob==>lucy 28 { 29 cout<<"拷贝构造函数"<<endl; 30 m_name = (char *)calloc(1, strlen(ob.m_name)+1); 31 cout<<"空间已被申请"<<endl; 32 strcpy(m_name, ob.m_name); 33 34 m_num = ob.m_num; 35 } 36 37 ~Person() 38 { 39 if(m_name != NULL) 40 { 41 cout<<"空间已被释放"<<endl; 42 free(m_name); 43 m_name = NULL; 44 } 45 cout<<"析构函数"<<endl; 46 } 47 48 void showPerson(void) 49 { 50 cout<<"m_name = "<<m_name<<", m_num = "<<m_num<<endl; 51 } 52 }; 53 54 void test01() 55 { 56 Person lucy("lucy",100); 57 lucy.showPerson(); 58 59 //浅拷贝的问题(多次释放同一块堆区空间) 60 //通过自定义 拷贝构造函数 完成深拷贝动作 61 Person bob = lucy;//调用系统的默认拷贝构造(单纯的值拷贝) 62 }
标签:实现 浅拷贝 默认 name 问题 test out vat char
原文地址:https://www.cnblogs.com/loliconinvincible/p/12521017.html