指向函数作为结构成员的指针在 C 中如何有用? [英] How pointers to function as struct member useful in C?

查看:27
本文介绍了指向函数作为结构成员的指针在 C 中如何有用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 C 编程并不陌生.但我不明白将指针保留为 C 中的结构成员有什么用处.例如

I am not new to C programming. But I don't understand what is usefulness to keep pointer to function as a structure member in C. e.g.

    // 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)形状并提供抽象对象?或者让代码看起来很有技术性.

Does programmers use it to give Object Oriented(OO) shape to there C code and provide abstract object? Or to make code look technical.

我认为,在上面的代码中,第二种方式更温和也很简单.首先,我们仍然需要通过 &var,即使 fun() 是 struct 的成员.

I think, in above code second way is more gentle and pretty simple too. In fist way, we still have to pass &var, even fun() is member of struct.

如果将函数指针保留在结构体定义中很好,请帮助解释原因.

If its good to keep function pointer within struct definition, kindly help to explain the the reason.

推荐答案

提供指向结构上的函数的指针可以让您动态选择要在结构上执行的函数.

Providing a pointer to function on a structure can enable you to dynamically choose which function to perform on a structure.

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);
    }

这使您能够拥有一个调用接口,但根据您的测试是否有效调用两个不同的函数.

This gives you the ability to have a single calling interface, but calling two different functions depending on if your test is valid or not.

这篇关于指向函数作为结构成员的指针在 C 中如何有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆