函式指標,與c++類的聯想
#include<stdio.h>
typedef void (*functionPointerType)(void); typedef struct commandstruct { char const* name; functionPointerType Pfunction; char const *help; }; void commVersion(); void cmdend(); void cmdflashtest();
const struct commandstruct commandstruct[]= { {"ver",&commVersion,"display firmware version"}, {"flash test",&cmdflashtest,"flash test"}, {"end",&cmdend,"end"} }; 3
void main() { int i=0; for(i=0;i<3;i++) { commandstruct[i].Pfunction(); } }
void commVersion() { int i=0; for(i=0;i<3;i++) { if(commandstruct[i].Pfunction==&commVersion) { printf("%s",commandstruct[i].help); break; } } }
void cmdflashtest() { int i=0; for(i=0;i<3;i++) { if(commandstruct[i].Pfunction==&cmdflashtest) { printf("%s",commandstruct[i].help); break; } } } void cmdend() { int i=0; for(i=0;i<3;i++) { if(commandstruct[i].Pfunction==&cmdend) { printf("%s",commandstruct[i].help); break; } } }
聯想到c++虛擬函式,通過指標的變換,決定執行對應虛擬函式