浅拷贝和深拷贝都是相对拷贝构造函数来讲的
下面代码实现浅拷贝,
1 #include <stdio.h> 2 #include <iostream> 3 #include <string> 4 using namespace std; 5 6 class A 7 { 8 public : 9 A(int a=0):m_num(a){}; 10 A(const A &arr); 11 int set_num(); 12 private: 13 int m_num; 14 }; 15 16 A::A(const A &arr) 17 { 18 m_num=arr.m_num; 19 } 20 int A::set_num() 21 { 22 return m_num; 23 } 24 int main (void) 25 { 26 A arr1(5); 27 A arr2(arr1); 28 cout << "arr1="<<arr1.set_num()<<endl<<"arr2="<<arr2.set_num()<<endl; 29 return 0; 30 }
再增加一个类成员指针变量,
1 #include <stdio.h> 2 #include <iostream> 3 #include <string> 4 using namespace std; 5 6 class A 7 { 8 public : 9 A(int a=0) 10 { 11 cout <<"A"<<endl; 12 m_num=a; 13 m_a=new int[m_num]; 14 }; 15 A(const A &arr); 16 int set_num(); 17 ~A(); 18 private: 19 int m_num; 20 int *m_a; 21 }; 22 23 A::A(const A &arr) 24 { 25 cout << "&A"<<endl; 26 m_a=arr.m_a; 27 m_num=arr.m_num; 28 } 29 int A::set_num() 30 { 31 return m_num; 32 } 33 A::~A() 34 { 35 cout << "~A"<<endl; 36 delete []m_a; 37 } 38 int main (void) 39 { 40 A arr1(5); 41 A arr2(arr1); 42 cout << "arr1="<<arr1.set_num()<<endl<<"arr2="<<arr2.set_num()<<endl; 43 return 0; 44 }
上面程序拷贝构造函数中把对象的指针地址拷贝给当前对象的指针地址,
当执行到析构函数,以为有两个对象,不是要删除两次吗,当运行第一次时没有问题,
当运行第二次程序就会崩溃。
那要解决这个问题就要深拷贝了。
1 #include <stdio.h> 2 #include <iostream> 3 #include <string> 4 using namespace std; 5 6 class A 7 { 8 public : 9 A(int a=0) 10 { 11 cout <<"A"<<endl; 12 m_num=a; 13 m_a=new int[m_num]; 14 }; 15 A(const A &arr); 16 int set_num(); 17 void set_m_a(); 18 ~A(); 19 private: 20 int m_num; 21 int *m_a; 22 }; 23 24 void A::set_m_a() 25 { 26 for (int i=0;i<m_num;i++) 27 { 28 m_a[i]=i; 29 cout << "m_a["<<i<<"]="<<m_a[i]<<endl; 30 } 31 32 } 33 A::A(const A &arr) 34 { 35 m_num=arr.m_num; 36 cout << "&A"<<endl; 37 m_a=new int [arr.m_num]; 38 for (int i=0;i<arr.m_num;i++) 39 { 40 m_a[i]=arr.m_a[i]; 41 } 42 43 44 } 45 int A::set_num() 46 { 47 return m_num; 48 } 49 A::~A() 50 { 51 cout << "~A"<<endl; 52 delete []m_a; 53 } 54 int main (void) 55 { 56 A arr1(5); 57 A arr2(arr1); 58 cout << "arr1="<<arr1.set_num()<<endl<<"arr2="<<arr2.set_num()<<endl; 59 cout << "arr1.m_a=";arr1.set_m_a(); 60 cout<<endl; 61 cout << "arr2.m_a=";arr2.set_m_a(); 62 return 0; 63 }
這样对象之间的赋值就不是地址之间的赋值,也不会同块内存中释放两次。
时间: 2024-11-11 03:24:59