#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;
}