一边听斯坦福大学的 Programming Abstractions当然,我遇到了一些如下所示的代码。
void plot(double start, double end, double (fn)(double)) {
double i;
for (i = start; i <= end; i += 1)
printf("fn(%f) = %f\n", i, fn(i));
}
double plus1(double x) {
return x + 1;
}
int main(void) {
plot(1, 10, plus1);
return 0;
}
我在我的系统上使用 GCC 编译了代码,然后是 G++;它们都运行完美。
我知道传递 int i = 2
进入函数,例如 void func1(int a)
将制作一份新拷贝 i
在传递 &i
时为该函数至 void func2(int *a)
只会给出函数 func2
i
的地址.
谁能给我解释一下传递fn
的机制是什么?至 plot
它与将函数指针作为参数传递有何不同?
最佳答案
void foo(double fn(double))
和 void foo(double (*fn)(double))
完全没有区别。两者都声明将指向函数的指针作为参数的函数。
这类似于 void bar(double arr[10])
和 void bar(double* arr)
之间没有区别的方式。
关于c++ - 函数作为参数 vs 函数指针作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9139689/