C++深复制与浅复制(七)

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


class CDemo
{
public:
CDemo(int pa,char *cstr)
{
this->a = pa;
this->str = new char[1024];
strcpy(this->str,cstr);
}

CDemo(CDemo & obj)
{
cout << "test" <<endl;
this->a = obj.a;
//    this->str = obj.str; //浅复制 


this->str = new char[1024];
if(str != NULL)
strcpy(this->str,obj.str);  //深复制

}


~CDemo()
{
delete str;
}


public:
int a;
char *str;
};


int main()
{
CDemo A(10,"hello");


CDemo B =A ;


cout << A.a<<"," << A.str << endl;
cout << B.a<<"," << B.str << endl;
B.a = 20 ;
B.str[0] = 'k';
cout << A.a<<"," << A.str << endl;
cout << B.a<<"," << B.str << endl;
return 0;
}

你可能感兴趣的:(C++深复制与浅复制(七))