-

来自「有限状态机设计与实现源代码.zip」· 代码 · 共 102 行

TXT
102
字号
/************用面向对象方法实现FSM的程序源代码******/
#include <iostream.h>

const int eventA=0;
const int eventB=1;
const int eventC=2;

class stateRoot{
public:
	virtual stateRoot* handleEventA()
	{
		return this;
	}
	virtual stateRoot* handleEventB()
	{
		return this;
	}
	virtual stateRoot* handleEventC()
	{
		return this;
	}
	virtual void printState()=0;
};
class stateA:public stateRoot{
public:
	virtual stateRoot* handleEventA();
	virtual stateRoot* handleEventB();
	virtual void printState()
	{
		cout<<"---->StateA"<<endl;
	}
};
class stateB:public stateRoot{
public:
	virtual stateRoot* handleEventA();
	virtual stateRoot* handleEventC();
	virtual void printState()
	{
		cout<<"---->StateB"<<endl;
	}
};
class stateC:public stateRoot{
public:
	virtual stateRoot* handleEventA();
	virtual void printState()
	{
		cout<<"---->StateC"<<endl;
	}
};
stateRoot* stateA::handleEventA()
{
	delete this;
	return new stateB;
};
stateRoot* stateA::handleEventB()
{
	delete this;
	return new stateC;
};
stateRoot* stateB::handleEventA()
{
	delete this;
	return new stateC;
};
stateRoot* stateB::handleEventC()
{
	delete this;
	return new stateA;
};
stateRoot* stateC::handleEventA()
{
	delete this;
	return new stateA;
};
void main()
{
	int event;
	stateRoot *currentstate=new stateA;
	while(1)
	{
		currentstate->printState();
		cout<<"type event:(0-3)"<<endl;
		cin>>event;
		switch(event)
		{
		case eventA:
			currentstate->handleEventA();
			break;
		case eventB:
			currentstate->handleEventB();
			break;
		case eventC:
			currentstate->handleEventC();
			break;
		default:
			cout<<"Unknown state"<<endl;

		}
	}
}

	

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?