1.浅拷贝
class Clothes
{
public:
Clothes(string name)
{
this->name = name;
}
public:
string name;
};
class Person
{
private:
int age;
string name;
Clothes* ptr_clothes;
public:
Person(int age,string name,string clo_name)
{
this->age = age;
this->name = name;
ptr_clothes = new Clothes(clo_name);
}
~Person()
{
if (ptr_clothes != NULL)
{
delete ptr_clothes;
ptr_clothes = NULL;
}
}
}
int main()
{
Person p1 = Person(10, "张三","李宁男装");
Person p2 = p1;
}
一个对象释放了内存,另外一个对象释放的时候,报错。
2.为了避免这个问题,深拷贝的解决思路为;
class Person
{
private:
int age;
string name;
Clothes* ptr_clothes;
public:
Person(int age,string name,string clo_name)
{
this->age = age;
this->name = name;
ptr_clothes = new Clothes(clo_name);
}
//深拷贝
Person(const Person& p)
{
this->age = p.age;
this->name = p.name;
this->ptr_clothes = new Clothes((p.ptr_clothes)->name); //
}
~Person()
{
if (ptr_clothes != NULL)
{
delete ptr_clothes;
ptr_clothes = NULL;
}
}
};