如何将函数指针传递到c++中的函数

How to pass function-pointer to a function in c++?

本文关键字:函数 c++ 指针      更新时间:2023-10-16

这里有三个函数,例如:-

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:中给出了一个错误

"错误C2064:术语的计算结果不是采用2个参数的函数"

现在,将函数"function_Pointer_func"中的"float(*pt2Func)(float,float)"参数替换为float(pt2Func)(float-floot),然后将所有三个

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++标准。

float Plus(float a, float b);
void Function_Pointer_func(float a, float b, float (*pt2Func)(float, float));
Function_Pointer_func(2, 5, Plus); // (1)
...
float result = pt2Func(a, b); // (2)

(1)是函数到指针的转换(标准2003,4.3):

An lvalue of function type T can be converted to an rvalue of
type “pointer to T.” The result is a pointer to the function

(2)是函数调用(标准2003,5.2.2):

For an ordinary function call, the postfix expression shall be either
an lvalue that refers to a function (in which case the function-to-pointer
standard conversion (4.3) is suppressed on the postfix expression), or it
shall have pointer to function type.

[更新]详细信息:

void Replace() { 
   Function_Pointer_func(2, 5, Plus);
   Function_Pointer_func(2, 5, &Minus);
}

减号是函数=>&Minus是指向函数的指针,因此没有转换,第三个参数Function_Pointer_func的完全匹配Plus是一个函数,因此要适应function_Pointer_func,必须将其转换为指针。标准(1)说它可以自动完成。

呼叫案例:

void Function_Pointer_func(float a, float b, float (*pt2Func)(float, float)) {
   float result = pt2Func(a, b); // call by pointer, see (2)
   float result = (*pt2Func)(a, b); // convert pointer to function, so 'normal' call
   float result = (&pt2Func)(a, b); // pointer to function pointer, nope, will not work
}