c继承的实现

c继承的实现,c,inheritance,macros,C,Inheritance,Macros,我正试图找出一种在c中进行半继承的好方法 这就是我想到的 //statemachine.h ... #define CHANGE_STATE(newState) \ do { \ printf("[%s]->", stateStrings[state]); \ state = newState;

我正试图找出一种在c中进行半继承的好方法

这就是我想到的

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

任何想成为状态机的模块(即利用CHANGE_state)都必须定义状态和状态字符串

只是在寻找关于这种方法的反馈

编辑:


问题转移到

使用继承的一种常见方法是在
struct
-s内部使用强制转换、
struct
,以及模拟(即指向包含函数指针的常量
struct
-s的指针)

例如,看看GTK的内部Glib。阅读并研究实现GObject的许多宏

//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);
}