C++有限状态机小例子

本篇用于记录写的一个FSM小demo,可能不太规范,自用。

#include <iostream>


using namespace std;

class FSM
{
public:
	enum class MyEnum
	{
		a,
		b,
		c,
		d
	};

	int FSM_step;
	MyEnum State;
	
	FSM()
	{
		cout << "FSM start..." << endl;
		this->FSM_step = 0;
		this->State = FSM::MyEnum::a;
		cout << "FSM_step = " << this->FSM_step << endl;
		cout << "Current state: " << int(this->State) << endl;
	}

	void FSM0();
	void FSM1();
	void FSM2();
	void FSM_end();
};

void FSM::FSM0()
{
	cout << "This is FSM0, your state is: a" << endl;
	while (1)
	{
		cout << "Please input state: ";
		cin >> this->FSM_step;

		if (this->FSM_step == 1)
		{
			this->State = FSM::MyEnum::a;
			cout << "FSM_step = " << this->FSM_step << endl;
			cout << "Current state: " << int(this->State) << endl;
			break;
		}
		if (this->FSM_step == 2)
		{
			this->State = FSM::MyEnum::b;
			cout << "FSM_step = " << this->FSM_step << endl;
			cout << "Current state: " << int(this->State) << endl;
			break;
		}
		if (this->FSM_step == 3)
		{
			this->State = FSM::MyEnum::c;
			cout << "FSM_step = " << this->FSM_step << endl;
			cout << "Current state: " << int(this->State) << endl;
			break;
		}
		if (this->FSM_step == 4)
		{
			this->State = FSM::MyEnum::d;
			cout << "FSM_step = " << this->FSM_step << endl;
			cout << "Current state: " << int(this->State) << endl;
			break;
		}
	}
}

void FSM::FSM1()
{
	cout << "This is FSM1, your state is: b" << endl;
	this->State = FSM::MyEnum::a;
}

void FSM::FSM2()
{
	cout << "This is FSM2, your state is: c" << endl;
	this->State = FSM::MyEnum::a;
}

void FSM::FSM_end()
{
	cout << "This is FSM_end, your state is: d" << endl;
	cout << "Exit program...." << endl;
	while (1)
	{

	}
}

int main()
{
	FSM f;

	while (1)
	{
		switch (f.State)
		{
			case FSM::MyEnum::a:f.FSM0(); break;
			case FSM::MyEnum::b:f.FSM1(); break;
			case FSM::MyEnum::c:f.FSM2(); break;
			case FSM::MyEnum::d:f.FSM_end(); break;
		default:
			break;
		}
	}
	return 0;
}

逐个输入状态尝试:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值