|
|||||||
|
|
|
![]() |
|
|
Strumenti |
|
|
#1 |
|
Senior Member
Iscritto dal: Apr 2000
Messaggi: 382
|
[C++] Macchina a stati finiti con puntatori a funzione
Salve a tutti,
desidererei chiedere il vostro aiuto per poter realizzare una macchina a stati finiti senza un utilizzo "intenso" del costrutto SWITCH, al fine di rendere il codice più leggibile e gestibile. In precedenza, ho sempre sempre utilizzato un codice simile a questo; Codice:
// StateMachine.cpp : definisce il punto di ingresso dell'applicazione.
//
#include "stdafx.h"
#define NSTATE 2
typedef void (*StateFunc)(void);
unsigned int state=0;
enum state
{
STATO1=0,
STATO2
};
static char * const stateStr[]= {"Stato 1","Stato 2"};
void enter_state1();
void enter_state2();
void exit_state1();
void exit_state2();
void state1() ;
void state2();
void goState(int _state);
const StateFunc state_machine [NSTATE] =
{
state1,
state2,
};
const StateFunc enter_state_machine [NSTATE] =
{
enter_state1,
enter_state2
};
const StateFunc exit_state_machine [NSTATE] =
{
exit_state1,
exit_state2
};
int _tmain(int argc, _TCHAR* argv[]){
int iter=0;
for (int i=0; i<10;i++){
printf("stato:%d - iter:%d - str:%s\n",state,iter,stateStr[state]);
if(state >= 0 && state <= NSTATE) {
state_machine[state]();
}
iter++;
}
getchar();
return 1;
}
void enter_state1() {
printf("Ingresso stato 1\n");
}
void enter_state2() {
printf("Ingresso stato 2\n");
}
void exit_state1() {
printf("Uscita stato 1\n");
}
void exit_state2() {
printf("Uscita stato 2\n");
}
void state1() {
printf("Sono nello stato 1\n");
goState(STATO2);
}
void state2() {
printf("Sono nello stato 2\n");
goState(STATO1);
}
void goState(int _state)
{
exit_state_machine[state]();
state=_state;
enter_state_machine[state]();
}
Codice:
const StateFunc state_machine [NSTATE] =
{
state1,
state2,
};
__________________
MacBook Pro Retina iPhone 4S 16GB |
|
|
|
|
|
#2 |
|
Senior Member
Iscritto dal: Apr 2000
Messaggi: 382
|
Caspita, ho appena risolto!
La scrittura del precedente post mi ha portato fortuna.. Codice:
state_machine[0]=&Classe::state1; state_machine[1]=&Controllo::state2; Codice:
void (Classe::*state_machine[2])(void); Codice:
(this->*state_machine[state])();
__________________
MacBook Pro Retina iPhone 4S 16GB |
|
|
|
|
| Strumenti | |
|
|
Tutti gli orari sono GMT +1. Ora sono le: 20:32.



















