#include <iostream>
#include <cstring>
using namespace std;
class A{
public:
char *p;
A(char *src){
p = new char[128];
strcpy(p,src);
}
A(A &a){ //重写复制构造器,为通过此构造器创建的对象在堆区开辟新的空间,进而在更改对象内容的时候,互相不影响,实现深度复制
p = new char[128];
strcpy(p,a.p);
}
~A(){
delete[] p;
}
};
int main()
{
A a("hello");
A b(a);
cout << a.p << endl;
cout << b.p << endl;
b.p[0]='k';
cout << a.p << endl;
cout << b.p << endl;
return 0;
}
#include <cstring>
using namespace std;
class A{
public:
char *p;
A(char *src){
p = new char[128];
strcpy(p,src);
}
A(A &a){ //重写复制构造器,为通过此构造器创建的对象在堆区开辟新的空间,进而在更改对象内容的时候,互相不影响,实现深度复制
p = new char[128];
strcpy(p,a.p);
}
~A(){
delete[] p;
}
};
int main()
{
A a("hello");
A b(a);
cout << a.p << endl;
cout << b.p << endl;
b.p[0]='k';
cout << a.p << endl;
cout << b.p << endl;
return 0;
}