我不是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);
}
Run Code Online (Sandbox Code Playgroud)
程序员是否使用它来为C代码提供面向对象(OO)形状并提供抽象对象?或者使代码看起来技术性.
我认为,在上面的代码中,第二种方式也更温和,也很简单.在第一种方式,我们仍然必须通过&var,甚至fun()是结构的成员.
如果将结构定义中的函数指针保持良好,请帮助解释其原因.
嘿家伙我有一个问题:如何从带有指针的枚举结构中调用函数?
例如,我有这样的结构:
typedef enum struct_e
{
FUNCTION_ONE,
FUNCTION_TWO,
FUNCTION_THREE,
FUNCTION_FOUR,
} sctruct_t;
Run Code Online (Sandbox Code Playgroud)
我有一个函数接收这些变量之一和函数的参数(例如int)
void call_functions(struct_t action, int exemple) {...}
// -> call like this call_functions(FUNCTION_ONE, 45);
Run Code Online (Sandbox Code Playgroud)
在该函数中,我必须调用以下函数之一:
void function_one(int a)
{
printf("You have %d years old", a);
}
Run Code Online (Sandbox Code Playgroud)