標籤:

C++的函數指針問題?

直接上代碼:

#include &
using namespace std;
void sum(int c){
cout&<&<"Called sum"&<&

這兩種寫法都行,而且運行結果一樣。這是為何?


簡單點說,就是規定是這樣的。

對於函數名:

函數名=*函數名=函數名

對於函數指針:

*函數指針=函數指針 != 函數指針


規定。


對一個函數指針使用一元*的結果是函數指示符(function designator),但是函數指示符會自動轉換成函數指針。

所以

void foo(void);

(foo)();

foo();

(*foo)();

(************************foo)();

都是一樣的。


剛才翻了一下C99的標準,請看

6.3.2.1

A function designator is an expression that has function type. Except when it is the operand of the sizeof operator or the unary operator, a function designator with type 『『function returning type』』 is converted to an expression that has type 『『pointer to function returning type』』.

6.5.3.2 Address and indirection operators

The operand of the unary operator shall be either a function designator...

The unary * operator denotes indirection. If the operand points to a function, the result is
a function designator;...


建議看 C專家編程 以及 C與指針 兩本書。


函數名就是一個地址常量,相當於const,所以怎麼解引用都不會變。


可以試試:

int main(void){
sum(5);
(*sum)(5);
(*********sum)(5);
}


sum也是指針


建議從彙編視圖來理解這個問題。


基於一些設計上的和實現上的考慮.沒什麼特別的目的.


推薦閱讀:

在c語言中,使用函數指針是否可以提高函數的調用速度 ?
不調用畫圖 API,用C 或 C++ 如何實現畫一條線?
編譯器生成的彙編語句執行順序為什麼與C代碼順序不同?
C++ 和 Objective-C 都可以 100% 翻譯為 C 代碼嗎?
Qt沒有真正完美的無邊框解決方案嗎?

TAG:CC |