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

标签 c++ function pointers

<分区>

我正在学习函数指针和来自 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;
}

如我所见,plus 是指向函数 add 的指针,它被传递给函数操作。很明显。但是 subtract 呢?

为什么不使用指针呢? 2种方法有什么区别?它是 c++ 特定的吗?

最佳答案

在C++中,函数可以自动转换为函数指针,所以下面是等价的:

b = operation(20, a, subtract);
b = operation(20, a, &subtract);

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

Is it c++ specific?

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

关于c++ - 通过指针和名称将函数传递给另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16956006/

相关文章:

c++ - 如何在 C 上使用 D3DXSaveTextureToFileW 将文件名保存为时间戳?

c++ - 更改 STL 多重集中两个相等元素的顺序

c++ - Serial.println 改变函数的返回值 (Arduino)

c++ - 使用指向 STL vector 的指针是个好主意吗?

c++ - 关于类成员函数指针的sizeof

c++ - 告诉 std::thread 在满足条件时终止/停止自身

c++ - 在同一个套接字上多次写入 C++

function - 如何减少 Golang 中重复函数的冗余代码?

mysql - MySQL如何知道一个段落包含多少个单词?

c++ - 条件运算符和数组/返回指向数组的指针