的指针对于目前的项目,我不能使用C++(不幸的),只有纯粹的C,和Im具有以下问题:获取结构调用函数
我有3个独特的结构需要调用同一个函数名,我觉得它的方式更优雅,而不是为不同类型创建3种不同的功能,就像我觉得它更容易维护。我怎样才能得到调用函数的指针?基本上我想重现的基本上与C++或self(在Obj-C)中的“this”类似,无论如何我可以在纯C中做到这一点?
[test.h]
enum
{
TYPE_A = 0,
TYPE_B = 1,
TYPE_C = 2
};
typedef struct
{
char type;
void (*GetType)(void);
// Some other data different than the other struct
}A;
typedef struct
{
char type;
void (*GetType)(void);
/* Some other data different than the other struct */
}B;
typedef struct
{
char type;
void (*GetType)(void);
// Some other data different than the other struct
} C;
A *create_a(void);
B *create_b(void);
C *create_c(void);
void GetType(void);
[test.c的]
A *create_a(void)
{
A *a = (A *) calloc(1, sizeof(A));
a->type = TYPE_A;
a->GetType = GetType;
return a;
}
B *create_b(void)
{
B *b = (B *) calloc(1, sizeof(B));
b->type = TYPE_B;
b->GetType = GetType;
return b;
}
C *create_c(void)
{
C *c = (C *) calloc(1, sizeof(C));
c->type = TYPE_C;
c->GetType = GetType;
return c;
}
void GetType(void)
{
printf("How to get the pointer that call this function to retrieve the type?");
}
[main.c中]
int main (int argc, const char * argv[])
{
A *a = create_a();
B *b = create_b();
C *c = create_c();
a->GetType();
b->GetType();
c->GetType();
return 0;
}
如果你足够深入这个兔子洞,你将最终重塑C++。 – 2011-04-28 08:13:33
但是只要我们重新实现C++,你应该使用vtables而不是每个对象的函数指针。 – 2011-04-28 08:15:54