- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
这是三个函数,例如:-
float Plus (float a, float b) { return a+b; }
float Minus (float a, float b) { return a-b; }
float Multiply(float a, float b) { return a*b; }
现在有一个函数将指向函数的指针作为参数之一:-
void Function_Pointer_func(float a, float b, float (*pt2Func)(float, float))
{
float result = pt2Func(a, b); // call using function pointer
cout << " Result = "; // display result
cout << result << endl;
}
并调用上面的函数“Function_Pointer_func”函数写在下面
void Replace()
{
Function_Pointer_func(2, 5, /* pointer to function 'Minus' */ Plus);//// (1)
Function_Pointer_func(2, 5, /* pointer to function 'Minus' */ &Minus);//// (2)
}
为什么上面的函数可以正常工作,因为函数“Function_Pointer_func”将函数指针作为参数。如果我们替换行中的 RHS
float result = pt2Func(a, b); // call using function pointer
函数“Function_Pointer_func”的 (*pt2Func)(a, b); 然后它也可以工作,但对于 (&pt2Func)(a, b);
它在 VS2008 中给出错误:
" error C2064: term does not evaluate to a function taking 2 arguments "
现在将函数“Function_Pointer_func”中“float (*pt2Func)(float, float)”的参数替换为 float (pt2Func)(float, float) 然后全部三个
float result = pt2Func(a, b); //
float result = (&pt2Func)(a, b); //
float result = (*pt2Func)(a, b); //
语句有效,为什么?我希望我不舒服的原因在于理解函数指针的核心理解。好吧,我不是在介绍Q吗?没有大量的阅读,但是是的,我没有对此进行任何深入的研究,所以请随时推荐一些这方面的阅读,这将解决我的歧义。
提前感谢您的帮助。
最佳答案
函数自动退化为函数指针。在这种情况下,
function_name
的真正含义是 &function_name
。
&function_name
将函数转换为函数指针。
*function_name
真正的意思是 *(function_name)
,根据上面的内容变成了 *(&function_name)
。 *
和 &
“抵消”,可以这么说,生成的 function_name
衰减回 &function_name
。
关于c++ - 如何将函数指针传递给 C++ 中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18193063/
我是一名优秀的程序员,十分优秀!