深拷贝

来源:互联网 发布:saber软件官网 编辑:程序博客网 时间:2024/05/01 18:35
 

什么时候调用拷贝构造函数

1--->当一个对象以值传递的方式传入函数

2--->当一个对象以值传递的方式返回函数

3--->当用一个对象初始化另一个对象时

拷贝构造函数分为浅拷贝和深拷贝

当类拥有堆内存资源时,必须用深拷贝

#include <iostream>#include <cstring>using namespace std;class DeepCopy{    public:    DeepCopy(int b,char* cstr)    {        a=b;        str=new char[b];        strcpy(str,cstr);    }    DeepCopy(const DeepCopy& C)    {        a=C.a;        str=new char[a]; //深拷贝        if(str!=0)        {            strcpy(str,C.str);        }    }    void Show()    {        cout<<str<<endl;    }    ~DeepCopy()    {        delete str;    }    private:    int a;    char *str;};int main(void){    DeepCopy A(10,"Hello!");    DeepCopy B=A;    B.Show();    return 0;}