如果您能向我解釋以下內容的含義,我將不勝感激:
void bar(char *a, char *b, unsigned short c) // (2)
{
...
}
void (*foo(void))(char *, char *, unsigned short) // (1)
{
return bar;
}
尤其是,
- 為什么(1)中沒有變數名?
- 是什么
void (*foo(void))意思?怎么可能*foo(void)是名字? - 是什么
return bar意思?回傳bar源代碼的地址,或者回傳結果bar,或者其他? - 使這些簽名如此復雜有什么特點嗎?
- 你能舉一個用法的例子嗎?
uj5u.com熱心網友回復:
foo是一個不帶引數的函式,并回傳一個指向函式的指標,該函式接受三個型別的引數char *,char *并且unsigned short回傳void。
這些宣告可能會非常令人困惑,因為它們應該由內而外地閱讀,并根據需要左右彈跳:
foo是一件事……foo(void)...顯然是一個功能*foo(void)...其回傳值可以取消參考(*foo(void))(...)...然后用這些引數呼叫void (*foo(void))(...)...這導致 type 的值void。
您還可以使用cdecl.org為您決議復雜的宣告:
將 foo 宣告為函式 (void) 回傳指向函式的指標 (指向 char、指向 char 的指標、unsigned short) 回傳 void
使用示例:
// Immediately call the returned function.
// The similarity to the declaration is no coincidence!
(*foo())("hello", "world", 42);
// Store the returned function pointer for later invocation.
// This time there are no parentheses following the name, because
// this is a variable, not a function.
void (*fnPtr)(char *, char *, unsigned short) = foo();
(*fnPtr)("hello", "world", 42);
如果函式內部沒有使用引數,則始終可以省略引數名稱。在這種情況下,甚至沒有函式體可以使用它們,因為函式體foo不是傳遞給引數的物件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/483991.html
