默认的拷贝构造函数是浅拷贝
数据成员是指针时会报错
#include<iostream>
using namespace std;
class MM
{
public:
MM(){}
MM(const char* str)
{
int length = strlen(str) + 1;
name = new char[length];
strcpy_s(name, length, str);
}
~MM()
{
if (name != nullptr)
{
delete name;
name = nullptr;
}
}
protected:
char* name;
};
int main()
{
MM girl("girl");
MM mm = girl; //调用拷贝构造函数
return 0;
}
浅拷贝,当指针成员时会出现问题,相当于指针都是指向同一位置,就会出现重复析构
深拷贝就不会报错,不会存在析构问题,各析构各的
#include<iostream>
using namespace std;
class MM
{
public:
MM(){}
MM(const char* str)
{
int length = strlen(str) + 1;
name = new char[length];
strcpy_s(name, length, str);
}
~MM()
{
if (name != nullptr)
{
delete[] name;
name = nullptr;
}
}
//浅拷贝
//MM(MM& object)
//{
// name = object.name;
//}
//深拷贝
MM(MM&object)
{
int length = strlen(object.name)+1;
name = new char[length];
strcpy_s(name, length, object.name);
}
protected:
char* name;
};
int main()
{
MM girl("girl");
MM mm = girl; //调用拷贝构造函数
return 0;
}