C++ c++;?
我知道当我们使用函数名作为值时,函数会自动转换为指针。 请看以下代码:C++ c++;?,c++,function,pointers,C++,Function,Pointers,我知道当我们使用函数名作为值时,函数会自动转换为指针。 请看以下代码: 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打印(int a) { 返回a; } i
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打印(int a)
{
返回a;
}
int main()
{
整数(*p)(整数)=打印;
整数(*q)(整数)=&print;
coutprint
不是指针。它的类型是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)
现在,当您通过p
调用print
时
p(8) //automatic dereferencing of p
(*p)(8) //manual dereferencing of p
print
是一个函数,但它可以隐式转换为函数指针类型。引用自:
指向指针的函数
函数类型T的左值可以隐式
已转换为指向该函数的prvalue指针。这不适用
指向非静态成员函数,因为引用
非静态成员函数不存在
因此,在你的情况下:
int (*p)(int) = print; // Conversion happens.
int (*q)(int) = &print; // Conversion does not happen.
隐式转换在需要使程序编译时自动启动,否则不会应用
关于函数调用,它是关于内置函数调用运算符()
。根据,内置函数调用运算符适用于引用函数的左值表达式和指向函数的指针。在您的情况下:
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) 指向函数的指针
我想这只是为了方便起见,在使用函数指针调用函数时,不必显式取消引用它们。如果使用typedefs
,则可以使用函数指针而不使用任何*
,这很可能与@SimonKraemer重复。谢谢。但链接仅解释了取消引用E,我的问题还包括函数PONT的分配。你的答案有一定的意义。但是在书中,C++入门第五版和许多其他的网站教程都说使用函数名作为rValy会把它转换成指针。所以我不知道你的答案是否是函数指针赋值的特殊条件。@ SyrdIGM是正确的。在我的回答中,他们指的是指针衰减函数。
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.