【问题标题】:Pass typedefed function pointer传递 typedefed 函数指针
【发布时间】:2016-03-08 11:30:21
【问题描述】:

我有两个具有相同签名的函数,我为它们定义了一个函数指针。此外,我定义了提到的函数指针以简化它的使用。代码如下:

int add(int first_op, int second_op)
{
    return first_op + second_op;
}

int subtract(int first_op, int second_op)
{
    return first_op - second_op;
}

typedef int (*functionPtr)(int, int);

int do_math(functionPtr, int first, int second){
    return functionPtr(first, second);
}

main() {
    int a=3, b=2;
    functionPtr f = &add;
    printf("Result of add = %d\n", f(a,b));

    f = &subtract;
    printf("Result of subtract = %d\n", f(a,b));
}

方法 do_math 出现两个错误,如下所示:

在函数“do_math”中:错误:参数名称省略 int do_math(functionPtr, int first, int second){

错误:'functionPtr'之前的预期表达式 return functionPtr(first, second);

我做错了什么?谢谢

【问题讨论】:

    标签: c function pointers compiler-errors


    【解决方案1】:

    functionPtr 是一种类型。参数还必须有名称:

    int do_math(functionPtr function, int first, int second){
        return function(first, second);
    }
    

    【讨论】:

      猜你喜欢
      • 2013-10-25
      • 1970-01-01
      • 2015-08-05
      • 2017-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多