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++具体是什么?
在C++中,函数可以自动转换为函数指针,因此以下内容是等效的:
b = operation(20, a, subtract);
b = operation(20, a, &subtract);
Run Code Online (Sandbox Code Playgroud)
由于&substract具有正确的类型(int (*)(int, int)),代码编译并按预期工作.
它是c ++特定的吗?
无法真正回答这个问题,因为可能还有其他语言允许这样做.我更确定有.