2016-03-08 73 views
1

我有兩個具有相同簽名的函數,我爲它們定義了一個函數指針。此外,我鍵入提到的函數指針來簡化它的使用。代碼如下:Pass typedefed函數指針

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兩個錯誤如下:

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

我做了什麼錯?謝謝

回答

4

functionPtr是一種類型。參數也必須有一個名稱:

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