c - 指向函数的指针如何在 C 中发挥作用?

标签 c oop struct coding-style structure

我对 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/

相关文章:

c - 链接器如何计算 .bss 部分的大小?

c - Tail 命令 - 使用 fseek() 和 getline() - 输出乱序

javascript - 如何编写具有高级报告功能的可维护的 JavaScript ala' Bash 脚本?

oop - "No appropriate method"使用类定义对象调用新函数时产生错误

c++ - 如何访问 mex 文件中 Matlab 结构数组中的数据

c - 对漏洞利用示例感到困惑?

c - 堆栈上的局部变量和 EBP 之间是什么?

php - 如何使继承成为可选的

c - 如何在 C 的结构中使用函数指针?

c++ - 具有结构和继承的初始化列表