我知道当我们使用函数名称作为值时,该函数会自动转换为指针。
看下面的代码:
int print(int a)
{
return a;
}
int main()
{
int (*p)(int) = print;
int (*q)(int) = &print;
cout << p(8) << endl;
cout << (*p)(8) << endl;
}
why are int (*p)(int) = print;
, print是一个指针,并且int (*p)(int) = &print;
, &打印是指针的地址,等价吗?
另一方面,当我们使用指向函数的指针来调用该函数时,为什么p(8)
and (*p)(8)
相等的?
print
is not一个指针。它的类型是int(int)
, not 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
现在当你打电话时print
通过p
,
p(8) //automatic dereferencing of p
(*p)(8) //manual dereferencing of p
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)