#include<iostream>
using namespace std;
class STRING{
public:
STRING(char *s)
{
cout<<"constructing called."<<endl;
ptr=new char[strlen(s)+1];
strcpy(ptr,s);
}
~STRING()
{
cout<<"destructing called.----"<<ptr<<endl;
delete []ptr;
}
STRING &operator=(const STRING &S);//实现“=”的重载(深拷贝)
private:
char *ptr;
};
STRING &STRING::operator =(const STRING &s)//实现“=”的重载(深拷贝)
{
if(this==&s) return *this;
delete []ptr;
ptr=new char[strlen(s.ptr)+1];
strcpy(ptr,s.ptr);
return *this;
}
int main()
{
STRING p1("HAHHJ");
STRING p2("jhdfu");
p2=p1;
return 0;
}
使用深拷贝解决指针悬挂问题(“=”运算符重载)
最新推荐文章于 2022-01-01 14:31:43 发布