[英]function pointer assignment and call in c++?
我知道當我們使用函數名稱作為值時,該函數會自動轉換為指針。 看下面的代碼:
int print(int a)
{
return a;
}
int main()
{
int (*p)(int) = print;
int (*q)(int) = &print;
cout << p(8) << endl;
cout << (*p)(8) << endl;
}
為什么int (*p)(int) = print;
, print是一個指針, int (*p)(int) = &print;
, &print是指向指針的地址,是否等效?
另一方面,當我們使用指向函數的指針來調用該函數時,為什么p(8)
和(*p)(8)
等效的?
print
不是指針。 它的類型是int(int)
,而不是int(*)(int)
。 這種區別在類型推導中尤其重要
auto& f = print; //type of f is int(&)(int), not int(*(&))(int)
template<typename Func>
foo(Func& f);
foo(print); //Func is deduced to be int(int), not int(*)(int)
與數組類似,您不能“按值”復制函數,但可以傳遞其地址。 例如,
int arr[4]; //the type of arr is int[4], not int*
int *a = arr; //automatic array-to-pointer decay
int (*a)[4] = &arr; //type match
int (*p)(int) = print; //automatic function-to-pointer decay
int (*p)(int) = &print; //type match
現在,當您通過p
調用print
時,
p(8) //automatic dereferencing of p
(*p)(8) //manual dereferencing of p
print
是一個函數,但是可以隱式轉換為函數指針類型。 引用cppref :
指針功能
函數類型T的左值可以隱式轉換為指向該函數的prvalue指針。 這不適用於非靜態成員函數,因為引用非靜態成員函數的左值不存在。
因此,在您的情況下:
int (*p)(int) = print; // Conversion happens.
int (*q)(int) = &print; // Conversion does not happen.
隱式轉換在需要進行程序編譯時會自動啟動,否則將不應用。
關於函數調用,它是關於內置函數調用operator ()
。 根據cppref ,內置函數調用運算符適用於引用函數的左值表達式和函數指針。 在您的情況下:
p(8); // The function call operator is applied to a pointer to function.
(*p)(8); // The function call operator is applied to an lvalue reference to function.
供您參考(重點是我的):
內置函數調用運算符
一個函數調用表達式,例如E(A1,A2,A3),由一個將函數命名為E的表達式組成,后跟一個括號中的表達式A1,A2,A3 ...的可能為空的列表。 命名函數的表達式可以是a) 引用函數的左值表達式
b) 函數指針
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.