[C++基础]021_浅拷贝和深拷贝

[C++基础]021_浅拷贝和深拷贝

 

浅拷贝:即类中有指针成员变量,拷贝时,只拷贝了指针变量,而没有拷贝指针变量所指向的地址块。

实例代码:

复制代码
 1 #include <iostream>
 2 using namespace std;
 3 
 4 class Tree{
 5 public:
 6     // 拷贝构造函数
 7     Tree(const Tree& tree){
 8         this->num = tree.num;
 9     }
10     // 构造函数
11     Tree(){
12         num = new int(10);
13     }
14     // 析构函数
15     ~Tree(){
16         delete num;
17     }
18     // 普通打印成员变量内容函数
19     void printNum(){
20         cout<<*(this->num)<<endl;
21     }
22 private:
23     int *num;
24 };
25 
26 int main(){
27     // 在堆里生成一个对象
28     Tree *tree1 = new Tree();
29     tree1->printNum();
30 
31     // 拷贝构造函数起作用了
32     Tree tree2(*tree1);
33     tree2.printNum();
34     
35     // 销毁tree1对象
36     delete tree1;
37     // 此时,num是悬空指针了
38     tree2.printNum();
39 
40     system("pause");
41     return 0;
42 }
复制代码

 

深拷贝:即复制对象时如有指针变量,那么也复制指针变量所指向的内存块。

实例代码:

复制代码
 1 #include <iostream>
 2 using namespace std;
 3 
 4 class Tree{
 5 public:
 6     // 拷贝构造函数(深拷贝)
 7     Tree(const Tree& tree){
 8         this->num = new int();
 9         *(this->num) = *(tree.num);
10     }
11     // 构造函数
12     Tree(){
13         num = new int(10);
14     }
15     // 析构函数
16     ~Tree(){
17         delete num;
18     }
19     // 普通打印成员变量内容函数
20     void printNum(){
21         cout<<*(this->num)<<endl;
22     }
23 public:// 这里为了方便,将成员变量声明为public,其实应该写一个获取成员变量的函数的
24     int *num;
25 };
26 
27 int main(){
28     // 在堆里生成一个对象
29     Tree *tree1 = new Tree();
30     tree1->printNum();
31 
32     // 拷贝构造函数起作用了
33     Tree tree2(*tree1);
34     tree2.printNum();
35     
36     // 销毁tree1对象
37     delete tree1;
38     // 此时,num是悬空指针了
39     tree2.printNum();
40 
41     system("pause");
42     return 0;
43 }
posted @ 2013-03-19 14:23  小薇林  阅读(161)  评论(0编辑  收藏  举报