c++ - 函数作为参数 vs 函数指针作为参数

标签 c++ c function parameters

一边听斯坦福大学的 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/

相关文章:

c++ - c99 : 63 characters of an internal name are significant?

c++ - CUDA 纹理和夹紧

c - Xcode 帮助 (C) : Console disappears and gives no output

c - void * 赋值问题

sql-server - sql server 函数中的 newid()

python - 我正在尝试创建一个输入名称并输出排名的函数。创建该功能的最佳方法是什么?

c++ - 切换到 clang 3.4 和 libc++ 时找不到标准 header

不使用范围运算符就无法访问 C++ 命名空间变量

c - 哈希表泄漏内存

javascript - 在 d3 中单击按钮执行 Javascript 文件