本篇用于记录写的一个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;
}
逐个输入状态尝试: