#include <iostream>
using namespace std;
class Test
{
public:
Test(const char*p)
{
this->len = strlen(p);
name = (char*)malloc((len+1)*sizeof(char));
strcpy(name,p);
}
Test(const Test &obj)//解决浅拷贝问题 提供深拷贝构造函数
{
this->len = obj.len;
name = (char*)malloc((len+1)*sizeof(char));
strcpy(name,obj.name);
}
~Test()//浅拷贝,同一块内存空间会析构两次 出现问题
{
if (name!=NULL)
{
free(name);
name = NULL;
len =0;
}
}
//重载等号操作符
Test& operator=(const Test &obj)
{
this->len = obj.len;
this->name = (char*)malloc((len+1)*sizeof(char));
strcpy(this->name,obj.name);
return *this;
}
void printName()
{
cout<<name<<endl;
}
void printLen()
{
cout<<len<<endl;
}
protected:
private:
char *name;
int len;
};
void display()
{
Test t("abc");
Test t2 = t;//t2调用拷贝构造函数
t2.printName();
}
void display2()
{
Test t("abc");
Test t2("efgh") ;
t2 = t;//如果不重载=操作符 此处也会出现问题,同一块内存空间被释放两次
t.printName();
}
int main()
{
display2();
system("pause");
return 0;
}
浅拷贝问题出现原因剖析
最新推荐文章于 2024-07-18 05:00:00 发布