编写此指针函数代码的长格式是什么?

What is the longform way of writing this pointer function code?

我是 C++ 新手。仍在努力思考回调在这种语言中的工作方式。

我有点理解指针函数,但我不明白它是如何工作的。

#include <iostream>

int add(int x, int y){
    return x+y;
}

int subtract(int x, int y){
    return x-y;
}

typedef int(*t_yetAnotherFunc)(int,int);
t_yetAnotherFunc doMoreMath(char op){
    if(op == '+')
        return add; // equivalent of add(x,y), where x and y are passed from the function calling doMoreMath()?
    else if(op == '-')
        return subtract;
}

int main(){
    int x = 2;
    int y = 22;
    t_yetAnotherFunc yetAnotherFunc=    doMoreMath('+');
    int yetAnotherFuncOutput=           yetAnotherFunc(x,y);
    std::cout << yetAnotherFuncOutput << '\n';

    return 0;
}

xy 如何从 yetAnotherFuncOutput 变成 yetAnotherFunc

或另一种提问方式:如果没有 typedef,这会是什么样子?

指向函数的指针可以像任何其他函数一样使用,当您调用它时,您会得到与调用任何其他函数一样的结果。这就像另一个函数的 别名

在您的情况下,您为 add 函数创建了一个 别名 ,当您调用 yetAnotherFunc 时,您实际上是在调用 add .

声明

int yetAnotherFuncOutput=           yetAnotherFunc(x,y);

相当于

int yetAnotherFuncOutput=           add(x,y);

让我们从typedef int(*t_yetAnotherFunc)(int,int)

开始

t_yetAnotherFunc 是可以指向一个方法的类型,该方法采用两个 int 作为参数,return 一个 int.

t_yetAnotherFunc doMoreMath(char op) 方法 returns addsubtract 基于 char op。 return 语句中的 addsubtract 必须被视为这些方法的地址,而不是函数调用。

t_yetAnotherFunc yetAnotherFuncc = doMoreMath('+');

根据t_yetAnotherFunc的定义,现在yetAnotherFuncc可以指向add方法。

如果您需要使用其指针(此处yetAnotherFuncc)调用具有参数 (int x, int y) 的函数(此处 add),则您需要通过其指针提供其参数作为 yetAnotherFuncc(x, y)。这是通过以下行完成的。

int yetAnotherFuncOutput = yetAnotherFunc(x,y);

它使用参数 x(2) 和 y (22) 以及 add 的 return 值调用函数 add存储在 yetAnotherFuncOutput.

没有typedef会是一个复杂的定义如下

int(*doMoreMath(char op))(int, int) {
  if(op == '+')
     return add
  else if(op == '-')
     return subtract;
}

int(*yetAnotherFunc)(int, int) = doMoreMath('+');