#include <time.h>
#include <stdlib.h>
//类的声明(只要在CGameRole中没有使用具体的对象就没有关系)
//如果在CGameRole中使用了具体的该声明的类的对象,那么这样声明也是没有用的
class CMemento;
class CGameRole
{
public:
void Init()
{
m_hp = 100;
m_def = 100;
m_attck = 100;
}
void ShowState()
{
printf("血量:%d\n",m_hp);
printf("防御值:%d\n", m_def);
printf("攻击值:%d\n\n", m_attck);
}
//战斗
void Fight()
{
srand((unsigned)time(nullptr));
m_hp -= rand() % 100;
m_def -= rand() % 100;
m_attck -= rand() % 100;
}
private:
int m_hp;
int m_def;
int m_attck;
friend CMemento; //直接使用备忘录类作为该游戏对象的友元类,感觉更方便呀,也不会破坏CGameRole的封装性
};
//备忘录
class CMemento
{
public:
CMemento()
{
m_pGameRole = nullptr;
}
void SaveState(CGameRole* pMemento)
{
m_pGameRole = new CGameRole;
m_pGameRole->m_attck = pMemento->m_attck;
m_pGameRole->m_def = pMemento->m_def;
m_pGameRole->m_hp = pMemento->m_hp;
}
void RecoverState(CGameRole* pMenento)
{
pMenento->m_attck = m_pGameRole->m_attck;
pMenento->m_def = m_pGameRole->m_def;
pMenento->m_hp = m_pGameRole->m_hp;
delete m_pGameRole;
m_pGameRole = nullptr;
}
private:
CGameRole* m_pGameRole;
};
int main()
{
//初始化角色
CGameRole* lixiaoyao = new CGameRole;
lixiaoyao->Init();
printf("战斗前:\n");
lixiaoyao->ShowState();
//使用备忘录对象来保存战斗之前的状态值
CMemento* pMemento = new CMemento;
pMemento->SaveState(lixiaoyao);
//角色战斗后
lixiaoyao->Fight();
printf("战斗后:\n");
lixiaoyao->ShowState();
printf("游戏回退之后:\n");
pMemento->RecoverState(lixiaoyao);
lixiaoyao->ShowState();
system("pause");
return 0;
}