原型模式(16)

举报
IM_STONE 发表于 2020/12/29 00:20:42 2020/12/29
【摘要】 原型模式 用原型指定创建对象的种类,并且通过拷贝这些原型创建新的对象 其关键点在于clone函数,调用clone函数来创建更多相同类型的对象 #include<iostream> #include<list> using namespace std; //父类 Resume:简历 class Resume { protected:...

原型模式

用原型指定创建对象的种类,并且通过拷贝这些原型创建新的对象
在这里插入图片描述
其关键点在于clone函数,调用clone函数来创建更多相同类型的对象

#include<iostream>
#include<list>
using namespace std;
//父类  Resume:简历
class Resume  
{  
protected: char *name;//有指针类型,防止浅拷贝
public: Resume() {} virtual ~Resume() {} virtual Resume* Clone() { return NULL; }  //关键函数
	virtual void Set(char *n) {} virtual void Show() {}  
}; class ResumeA : public Resume  
{  
public: ResumeA(){}
	ResumeA(char *str);  //构造函数  
	ResumeA(const ResumeA &r); //拷贝构造函数  
	~ResumeA(); //析构函数  
	ResumeA* Clone(); //克隆,关键所在  
	void Show(); //显示内容  
};  
ResumeA::ResumeA(char *str) { if(str == NULL) 
	{ name = new char[1]; name[0] = '\0'; } else//切记要深拷贝,不要浅拷贝
	{ name = new char[strlen(str)+1]; strcpy(name, str); } //浅拷贝代码如下
	//name = str;
}  
ResumeA::~ResumeA()
{ 
	delete [] name;
}  
ResumeA::ResumeA(const ResumeA &r)
{ name = new char[strlen(r.name)+1]; strcpy(name, r.name);  
}  
ResumeA* ResumeA::Clone() 
{ return new ResumeA(*this); 
	//直接调用类的拷贝构造函数
	//其实也可以在本函数内自己实现拷贝构造函数的内容
	//代码如下
	/*
	ResumeA * m_sum = new ResumeA();
	if(name == NULL) 
	{ m_sum->name = new char[1]; m_sum->name[0] = '\0'; } else//切记要深拷贝,不要浅拷贝
	{ m_sum->name = new char[strlen(name)+1]; strcpy(m_sum->name, name); } return m_sum;
	*/
}  
void ResumeA::Show()
{ cout<<"ResumeA name : "<<name<<endl; } int main()  
{ Resume *r1 = new ResumeA("A"); Resume *r2 = new ResumeA("B"); Resume *r3 = r1->Clone(); Resume *r4 = r2->Clone(); r1->Show(); r2->Show(); //删除r1,r2  
	delete r1; delete r2; r1 = r2 = NULL; cout<<"-----------------------"<<endl;
	//深拷贝所以对r3,r4无影响  
	r3->Show();
	r4->Show(); delete r3; delete r4; r3 = r4 = NULL;  
}


  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96

文章来源: blog.csdn.net,作者:IM-STONE,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/doubleintfloat/article/details/110455397

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。