原理:拷贝自身对象实际上就是调用的拷贝构造函数,注意事项是这里的拷贝是深拷贝,即需要拷贝指针所指的内容
#include <stdio.h>
#include <memory>
#include <iostream>
class Resume
{
public:
virtual Resume* Clone(){return NULL;}
virtual ~Resume(){}
protected:
char *name;
};
class ResumeA:public Resume
{
public:
ResumeA(const char* str);
Resume* Clone();
ResumeA(const ResumeA& r);
~ResumeA();
};
ResumeA::ResumeA(const char* str)
{
if (str == NULL)
{
name= new char[1];
name[0] = '\0';
}
else
{
int length = strlen(str);
name = new char[length + 1];
strcpy(name,str);
name[length] = '\0';
}
}
ResumeA::ResumeA(const ResumeA& r)
{
int length = strlen(r.name);
name = new char[length + 1];
strcpy(name,r.name);
}
Resume* ResumeA::Clone()
{
return new Resume(*this);
}
int main()
{
Resume* pObja= new ResumeA("abc");
Resume* pCloneObja= pObja->Clone();
delete pObja;
delete pCloneObja;
return 0;
}