2014-09-18 78 views
0

我想弄清楚在c中做半繼承的一個好方法。c繼承的實現

這是我想出

//statemachine.h 
... 
#define CHANGE_STATE(newState)     \ 
    do {           \ 
     printf("[%s]->", stateStrings[state]); \ 
     state = newState;      \ 
     printf("[%s]\r\n", stateStrings[state]); \ 
    } while (0) 

//trafficlight.c 
#include "trafficlight.h" 
#include "statemachine.h" 

// Is a state machine 
typedef enum { 
    green, 
    yellow, 
    red 
} traffic_state; 

static const char * stateStrings [] = { 
    "green", 
    "yellow", 
    "red" 
}; 

static traffic_state state = red; 

// Move to the next signal 
void lightChange(void) { 
    CHANGE_STATE((state+1)%3); 
} 

這個想法是,要成爲一個狀態機的任何模塊(即利用CHANGE_STATE的)必須定義狀態和stateStrings。

只需尋找有關此方法的反饋。

編輯:

問題移到codereview

回答

1

使用繼承的一個常見方法是使用管型,struct內部struct -s和模擬vtables(即指針的含函數指針恆定struct -s) 。

查看來自GTK的Glib內部GObject的示例。閱讀Gobject documentation並研究實現GObject的許多宏。