案例
#include <iostream>
#include <string.h>
using namespace std;
class Demo
{
public:
Demo(int pa, char *cstr)
{
this->a = pa;
this->str = new char[1024];
strcpy(this->str, cstr);
}
public:
int a;
char *str;
};
int main()
{
Demo A(10, "hello");
Demo B = A; // 复制
cout << "复制结果:" << endl;
cout << A.a << " " << A.str << endl;
cout << B.a << " " << B.str << endl;
B.a = 8; // 只修改了B
B.str[0] = 'k';
cout << endl;
cout << "只修改了B:" << endl;
cout << A.a << " " << A.str << endl;
cout << B.a << " " << B.str << endl;
return 0;
}
运行结果:
复制结果:
10 hello
10 hello
只修改了B:
10 kello
8 kello
A居然也被修改了,这就是浅拷贝(浅复制)引起的
很多时候出现这种情况,是我们不愿意看到的,所以我们要用深拷贝(深复制)
#include <iostream>
#include <string.h>
using namespace std;
class Demo
{
public:
Demo(int pa, char *cstr)
{
this->a = pa;
this->str = new char[1024];
strcpy(this->str, cstr);
}
// 创建复制构造函数
Demo(Demo &obj)
{
this->a = obj.a;
// 深拷贝 创建新的指针
this->str = new char[1024];
if (str != 0)
strcpy(this->str, obj.str);
}
// 析构函数 消除指针
~Demo()
{
delete str;
}
public:
int a;
char *str;
};
int main()
{
Demo A(10, "hello");
Demo B = A; // 复制
cout << "复制结果:" << endl;
cout << "A: " << A.a << " " << A.str << endl;
cout << "B: " << B.a << " " << B.str << endl;
B.a = 8; // 只修改了B
B.str[0] = 'k';
cout << endl;
cout << "只修改了B:" << endl;
cout << "A: " << A.a << " " << A.str << endl;
cout << "B: " << B.a << " " << B.str << endl;
return 0;
}
运行结果:
复制结果:
A: 10 hello
B: 10 hello
只修改了B:
A: 10 hello
B: 8 kello