标签:style blog http color os strong io 2014
这一篇只有代码
// State.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
//强制声明
class CMe;
//状态抽象基类
class CState
{
public:
CState();
virtual ~CState();
virtual void Show(CMe* pMe) = 0;
};
CState::CState(){}
CState::~CState(){}
//单身状态类
class CSingle : public CState
{
public:
CSingle();
virtual ~CSingle();
virtual void Show(CMe* pMe);
};
CSingle::CSingle(){}
CSingle::~CSingle(){}
void CSingle::Show(CMe* pMe)
{
cout << endl << "哥哥是单身狗啊单身狗!!!" << endl;
}
//有女朋友状态类
class CWithGirl : public CState
{
public:
CWithGirl();
virtual ~CWithGirl();
virtual void Show(CMe* pMe) ;
};
CWithGirl::CWithGirl(){}
CWithGirl::~CWithGirl(){}
void CWithGirl::Show(CMe* pMe)
{
cout << endl << "哥哥有女朋友了啊好幸福!!!" << endl;
}
//我 类
class CMe
{
public:
CMe();
virtual ~CMe();
void SetState(CState* pState); //设置状态
void ShowMsg(); //显示此状态的信息
protected:
CState* m_ptrState;
};
CMe::CMe() : m_ptrState(NULL){}
CMe::~CMe(){}
void CMe::SetState(CState* pState)
{
m_ptrState = pState;
}
void CMe::ShowMsg()
{
m_ptrState->Show(this);
}
int _tmain(int argc, _TCHAR* argv[])
{
CMe me1;
me1.SetState(new CSingle());
me1.ShowMsg();
cout << endl << endl;
me1.SetState(new CWithGirl());
me1.ShowMsg();
cout << endl << endl;
return 0;
}
执行结果
具体解释见下一篇
标签:style blog http color os strong io 2014
原文地址:http://www.cnblogs.com/cuish/p/3868529.html