[英]How to set the argument of a function pointer of type its parent structure
I try to define function pointers as the members of the structure which can access and modify other parameters of the structure (like functions of a class in OOP). 我尝试将函数指针定义为结构的成员,这些成员可以访问和修改结构的其他参数(例如OOP中类的函数)。
For this, I have a structure with two function pointers: 为此,我有一个带有两个函数指针的结构:
typedef struct{
int a;
int b;
int (*init)(); // line 4
int (*multiply)(); // line 5
}STR_X2;
where the function pointers are defined as follows: 函数指针的定义如下:
void init(STR_X2* self , int _a , int _b){
self->a = _a;
self->b = _b;
printf("Init a:%d, b:%d \n",self->a,self->b);
}
int multiply(STR_X2* self){
printf("Multiply a:%d, b:%d, res:%d\n",self->a,self->b,self->a*self->b);
return self->a*self->b;
}
and then I use the structure in main()
function as follows: 然后使用main()
函数中的结构,如下所示:
int main(void) {
STR_X2* val2;
val2->init = init;
val2->multiply = multiply;
val2->init(val2,7,5);
printf("result:%d\n",val2->multiply(val2));
return EXIT_SUCCESS;
}
both function pointers have one argoment of type STR_X2
. 这两个函数指针都有一个类型为STR_X2
。 But logically I cannot define this argument because the structure STR_X2
is not defined at line 4 and 5. 但是从逻辑STR_X2
我无法定义此参数,因为未在第4行和第5行定义STR_X2
结构。
My question: 我的问题:
Is this way of defining function pointer (without argument) safe? 这样定义函数指针(不带参数)是否安全?
Is there any better alternative to access the structure member in such function pointers? 有没有更好的选择来访问此类函数指针中的结构成员?
Basically what you want here is a forward declaration of a structure type. 基本上,您想要的是结构类型的前向声明。 You can achieve this by using structure tags. 您可以通过使用结构标签来实现。 For example: 例如:
typedef struct STR_X2_S STR_X2;
struct STR_X2_S {
int a;
int b;
int (*init)(STR_X2 *self, int _a, int _b);
int (*multiply)(STR_X2 *self);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.