传递typedefed函数指针(Pass typedefed function pointer)

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

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'中:error:参数名省略int do_math(functionPtr,int first,int second){

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

我做错了什么? 谢谢

I have two functions with the same signature and i defined a function pointer for them. Additionally, i typedefed the mentioned function pointer to simplify use of it. The code is like:

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

I get two errors for method do_math as follows:

In function ‘do_math’: error: parameter name omitted int do_math(functionPtr, int first, int second){

error: expected expression before ‘functionPtr’ return functionPtr(first, second);

What i have done wrong? Thanks

最满意答案

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

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

functionPtr is a type. Parameters must also have a name:

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

更多推荐