我希望了解如何在C结构体中使用函数指针来模拟面向对象编程,但在我的搜索中,我只发现了一些问题,例如这个,其中的答案仅仅是使用函数指针,而没有描述它的工作原理。
我的最佳猜测是像这样:
我的最佳猜测是像这样:
#include <stdio.h>
#include <stdlib.h>
struct my_struct
{
int data;
struct my_struct* (*set_data) (int);
};
struct my_struct* my_struct_set_data(struct my_struct* m, int new_data)
{
m->data = new_data;
return m;
}
struct my_struct* my_struct_create() {
struct my_struct* result = malloc((sizeof(struct my_struct)));
result->data = 0;
result->set_data = my_struct_set_data;
return result;
}
int main(int argc, const char* argv[])
{
struct my_struct* thing = my_struct_create();
thing->set_data(1);
printf("%d\n", thing->data);
free(thing);
return 0;
}
但是这给我带来了编译器警告warning: assignment from incompatible pointer type
,所以显然我做错了什么。有人能否提供一个小而完整的示例,说明如何正确地在C结构中使用函数指针?
我的C语言课程甚至没有提到这些。这让我想知道C程序员是否真正使用它们。在C结构中使用函数指针的优缺点是什么?
(struct my_struct*,int)
,而结构定义仅具有(int)
。 - pb2qmy_struct_set_data()
分配给它,那么你应该将结构定义中的函数指针更改为struct my_struct* (*set_data) (struct my_struct*, int);
。 - eddieantonio