如何指针的功能在C有用结构成员? [英] How pointers to function as struct member useful in C?

查看:104
本文介绍了如何指针的功能在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);    
    }

难道程序员用它来给定向(OO)的物体形状为有C code和提供抽象的对象呢?或者使code看技术。

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

我认为,在上述code第二种方式是比较温柔pretty很简单。在拳头的方式,我们还是要通过&放大器; VAR ,甚至乐趣()是结构的成员。

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=fun;
        else
          var.f=fun2;
        usevar(var);
    }

这让你保持只有一个code的能力,但调用两个不同的功能,而你的测试是否有效。

This give you the ability to maintain only one code, but calling two different function rather your test is valid or not.

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

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