gpt4 book ai didi

c++ - 如何将函数指针传递给 C++ 中的函数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:54:40 25 4
gpt4 key购买 nike

这是三个函数,例如:-

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com