C++之拷贝构造函数、深拷贝、浅拷贝

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
 
/*
    CopyConstructor.cpp
    Author: Michael Joessy
    Date: 2017-06-07
    Marks:
    如果没有自定义拷贝构造函数,则系统会自动生成一个默认的拷贝构造函数(什么也不输出)。
    当采用直接初始化或复制初始化实例化对象时,系统自动调用拷贝构造函数。

    对象间的拷贝分为:深拷贝 和 浅拷贝
    浅拷贝:只是将数据成员的值进行了拷贝
    深拷贝:涉及到指针时,特别注意!
    在某些状况下,类内成员变量需要动态开辟堆内存,如果实行浅拷贝,如A = B。
    这时,如果B中有一个成员变量指针已经申请了内存,那A中的那个成员变量也指向同一块内存。
    这就出现了问题:当B把内存释放了(如:析构),这时A内的指针就是野指针了,出现运行错误。
*/


#include <iostream>
#include <string>
using namespace std;


class Student
{
public:
    
//无参构造函数,即默认构造函数
    Student()
    {
        cout << 
"Student" << endl;
    }
    
//定义拷贝构造函数
    //定义格式:类名(const 类名& 变量名)
    Student(const Student &stu)
    {
        cout << 
"Copy Student" << endl;
    }
protected:
private:
    string m_strName;
};


/* 深拷贝和浅拷贝可以简单理解为:
    如果一个类拥有资源,当这个类的对象发生复制过程的时候,资源重新分配,这个过程就是深拷贝;
    反之,没有重新分配资源,就是浅拷贝。
*/

class MyArray
{
public:
    MyArray()
    {
        m_nCount = 
5;
        m_pArr = 
new int[m_nCount];
    }
    MyArray(
const MyArray &arr)
    {
        m_nCount = arr.m_nCount;
        
//m_pArr = arr.m_pArr;          //浅拷贝,隐患大
        m_pArr = new int[m_nCount];     //深拷贝,重新申请另一块内存
        for (int i = 0; i < m_nCount; i++)
        {
            m_pArr[i] = arr.m_pArr[i];
        }
    }
protected:
private:
    
int m_nCount;
    
int *m_pArr;
};

int main(void)
{
    
//拷贝构造函数
    Student std1;
    Student std2 = std1;
    Student std3(std1);

    
//深拷贝和浅拷贝
    MyArray arr1;
    MyArray arr2 = arr1;

    cin.get();
    
return 0;
}

posted on 2017-06-07 15:55  我来乔23  阅读(219)  评论(0编辑  收藏  举报

导航