我对 C 编程并不陌生。但我不明白将指针作为结构成员保留在 C 中有什么用处。例如
// Fist Way: To keep pointer to function in struct
struct newtype{
int a;
char c;
int (*f)(struct newtype*);
} var;
int fun(struct newtype* v){
return v->a;
}
// Second way: Simple
struct newtype2{
int a;
char c;
} var2;
int fun2(struct newtype2* v){
return v->a;
}
int main(){
// Fist: Require two steps
var.f=fun;
var.f(&var);
//Second : simple to call
fun2(&var2);
}
程序员是否使用它来为 C 代码提供面向对象 (OO) 的形状并提供抽象对象?或者使代码看起来技术性。
我认为,在上面的代码中,第二种方式更温和,也非常简单。在第一种方式中,我们仍然必须传递 &var
,即使 fun()
是 struct 的成员。
如果将函数指针保留在结构定义中有好处,请帮助解释原因。
最佳答案
提供指向结构上的函数的指针可以让您动态地选择要在结构上执行的函数。
struct newtype{
int a;
int b;
char c;
int (*f)(struct newtype*);
} var;
int fun1(struct newtype* v){
return v->a;
}
int fun2(struct newtype* v){
return v->b;
}
void usevar(struct newtype* v) {
// at this step, you have no idea of which function will be called
var.f(&var);
}
int main(){
if (/* some test to define what function you want)*/)
var.f=fun1;
else
var.f=fun2;
usevar(var);
}
这使您能够拥有一个调用接口(interface),但根据您的测试是否有效调用两个不同的函数。
关于c - 指向函数的指针如何在 C 中发挥作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12971995/