听到一哥们碰到一个面试题,说使用C模拟一个类。我们知道C中是没有类的概念的,那我们怎么使用C模拟类呢?其实我们的办法并不多,宏定义可能会是一个不错的选择,下面是简单的尝试。
#define Struct_S \
int a;\
int b;\
int c
struct S
{
Struct_S;
};
#define Struct_H \
Struct_S; \
float e; \
float f
struct H
{
Struct_H;
};
//成员函数
typedef struct S S;
typedef struct H H;
static void s_mem_function(S *obj_s)
{
}
static void h_mem_function(H *obj_h)
{
}
上面是简单的模拟了继承和成员函数的实现。其实,对于成员函数,也可以进一步模拟函数表,但是那样可能会显得啰嗦不自然,具体如下:
//函数表
struct FuncTable_S
{
void (*s_mem_function_1)(S *obj_s);
void (*s_mem_function_2)(S *obj_s);
}
struct S
{
Struct_S;
struct FuncTable_S funct_s;
};
这样以来调用的时候,会出现s->functt_s->s_function_1多重指定的问题,看着别扭。不如直接使用上面的形式方便。
其实能使用C的地方绝大多数时候都能使用C++,与其使用C去模拟C++现实类的特性,大多数时候还不如直接使用C++呢。