深拷贝的两步骤实现方法-①拷贝构造函数②赋值操作符重载

 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 class Test{
 5 private:
 6         int*m_pointer;
 7 public:
 8         Test(){
 9                 m_pointer = NULL;
10         }
11         Test(int i){
12                 m_pointer = new int(i);
13         }
14         //深拷贝要完成的2件事 ① 拷贝构造函数
15         Test(const Test& obj){
16                 m_pointer = new int(*obj.m_pointer);
17         }
18         //② 操作符函数重载
19         //返回值是引用的原因:连续赋值;且参数也必须是const引用
20         Test& operator = (const Test& obj){
21                 //避免自己赋值给自己
22                 if(this != &obj){
23                         //此处才进行深拷贝
24                         delete m_pointer;
25                         m_pointer = new int(*obj.m_pointer);
26                 }
27         //返回当前对象
28         return *this;
29         }
30        }
31         void print(){
32                 cout << "m_pointer=" << m_pointer << endl;
33 }
34         //只有在堆空间申请内存的时候才会自定义析构函数
35         //栈上的内存不用自定义析构函数
36         ~Test(){
37                 delete m_pointer;
38         }
39 };
40 int main(){
41         Test t1(25);
42         Test  t2;
43         t2 = t1;
44         t1.print();
45         t2.print();
46         return 0;
47 }
48 
49 
50 运行结果:
51 m_pointer=0x2309c20
52 m_pointer=0x2309c40

猜你喜欢

转载自www.cnblogs.com/DXGG-Bond/p/11874073.html