通过指针和名称将函数传递给另一个函数

Via*_*iuk 4 c++ pointers function

我正在学习函数指针和wiki的这个例子:

int add(int first, int second)
{
    return first + second;
}

int subtract(int first, int second)
{
    return first - second;
}

int operation(int first, int second, int (*functocall)(int, int))
{
    return (*functocall)(first, second);
}

int main()
{
    int  a, b;
    int  (*plus)(int, int) = add;
    a = operation(7, 5, plus);
    b = operation(20, a, subtract);
    cout << "a = " << a << " and b = " << b << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

正如我所看到的,有plus一个指向函数的指针add,它被传递给函数操作.很明显.但是呢subtract.

为什么没有使用指针呢?两种方法有什么区别?c++具体是什么?

Luc*_*ore 7

在C++中,函数可以自动转换为函数指针,因此以下内容是等效的:

b = operation(20, a, subtract);
b = operation(20, a, &subtract);
Run Code Online (Sandbox Code Playgroud)

由于&substract具有正确的类型(int (*)(int, int)),代码编译并按预期工作.

它是c ++特定的吗?

无法真正回答这个问题,因为可能还有其他语言允许这样做.我更确定有.

  • 实际上,同样的隐式转换也发生在`plus`的定义中,没有它就必须以`=&add;`结尾. (3认同)