#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
#include "string"
class Person
{
public:
virtual Person* Clone() = 0;
virtual void Print() = 0;
virtual void setDescribe(char *) = 0;
};
class CPlusPlusProgramer :public Person
{
public:
CPlusPlusProgramer()
{
m_name = "";
m_age = 0;
m_describe = NULL;
}
CPlusPlusProgramer(string name, int age)
{
m_name = name;
m_age = age;
}
void setDescribe(char *describe)
{
if (m_describe != NULL)
{
delete m_describe;
}
m_describe = new char[strlen(describe) + 1];
strcpy(m_describe, describe);
}
virtual Person *Clone()
{
CPlusPlusProgramer *tmp = new CPlusPlusProgramer;//采用无参构造函数
tmp->m_describe = new char[strlen(m_describe) + 1];
strcpy(tmp->m_describe, m_describe);
//*tmp=*this;
tmp->m_age = m_age;
tmp->m_name = m_name;
return tmp;
}
virtual void Print()
{
cout << "m_name" << m_name << " m_age" << m_age << " m_describe" << m_describe << endl;
}
private:
string m_name;
int m_age;
char *m_describe;
};
void main()
{
Person *b = new CPlusPlusProgramer("张三", 32);
b->setDescribe("一个牛逼的C++程序员!");
b->Print();
Person *c = new CPlusPlusProgramer();
c = b->Clone();
delete b;
c->Print();
delete c;
}
原型模式
最新推荐文章于 2024-08-18 00:40:09 发布