2011-11-06 123 views

回答

4
void (*fun(double, int))(); 

按照right-left-rulefundouble, int返回一個指針與不確定參數的函數的函數返回void

編輯:This是該規則的另一個鏈接。編輯2:這個版本只是爲了緊湊和表明它確實可以完成。

這裏使用typedef確實很有用。但不是指針,而是到函數類型本身

爲什麼?因爲可以將它用作一種原型,所以確保函數確實匹配。並且因爲指針的身份保持可見。

所以一個好的解決辦法是

typedef char specialfunc(); 
specialfunc * myFunction(double, int); 

specialfunc specfunc1; // this ensures that the next function remains untampered 
char specfunc1() { 
    return 'A'; 
} 

specialfunc specfunc2; // this ensures that the next function remains untampered 
// here I obediently changed char to int -> compiler throws error thanks to the line above. 
int specfunc2() { 
    return 'B'; 
} 

specialfunc * myFunction(double value, int threshold) 
{ 
    if (value > threshold) { 
     return specfunc1; 
    } else { 
     return specfunc2; 
    } 
} 
+0

感謝您的編輯,但我已經給您接受+1。那正是我在尋找的。 –

+0

Thx。我只是想a)要清楚,b)給出良好實踐的提示。 – glglgl

12

typedef是你的朋友:

typedef char (*func_ptr_type)(); 
func_ptr_type myFunction(double, int); 
+0

給予好評「因爲我從來沒有想到這一點!謝謝。 –

3

做一個typedef:

typedef int (*intfunc)(void); 

int hello(void) 
{ 
    return 1; 
} 

intfunc hello_generator(void) 
{ 
    return hello; 
} 

int main(void) 
{ 
    intfunc h = hello_generator(); 
    return h(); 
} 
+0

upvote here也出於同樣的原因和相同的感謝。 –

0
char * func() { return 's'; } 

typedef char(*myPointer)(); 
myPointer myFunctionA (double, int){ /*Implementation*/ return &func; }