Advertisement
Guest User

FSM using member function pointers

a guest
Sep 4th, 2015
579
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.71 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. class Fsm
  6. {
  7. public:
  8.     Fsm() : state(&Fsm::initState) {}
  9.    
  10.     void run(int i)
  11.     {
  12.         (this->*state)(i);
  13.     }
  14.    
  15. private:
  16.     void initState(int i)
  17.     {
  18.         if(i>=0) state=&Fsm::statePositive;
  19.         else state=&Fsm::stateNegative;
  20.     }
  21.    
  22.     void statePositive(int i)
  23.     {
  24.         cout<<"Last number was positive"<<endl;
  25.         if(i>=0) state=&Fsm::statePositive;
  26.         else state=&Fsm::stateNegative;
  27.     }
  28.    
  29.     void stateNegative(int i)
  30.     {
  31.         cout<<"Last number was negative"<<endl;
  32.         if(i>=0) state=&Fsm::statePositive;
  33.         else state=&Fsm::stateNegative;
  34.     }
  35.    
  36.     void (Fsm::* state)(int);
  37. };
  38.  
  39. int main()
  40. {
  41.     Fsm fsm1;
  42.     Fsm fsm2;
  43.    
  44.     fsm1.run(10);
  45.     fsm2.run(-2);
  46.     fsm1.run(0);
  47.     fsm2.run(0);
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement