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

标签 c++ function-pointers typedef

我是 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 如何从 yetAnotherFuncOutputyetAnotherFunc

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

最佳答案

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

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

声明

int yetAnotherFuncOutput=           yetAnotherFunc(x,y);

相当于

int yetAnotherFuncOutput=           add(x,y);

关于c++ - 编写此指针函数代码的长格式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34987049/

相关文章:

ios - 如何根据我的需要创建一个新的 iOS 框架?

c - c中分配错误中的不兼容类型

c++ - 从函数内部更改函数指针的目标有什么问题吗? (C++)

c++ - 取消引用函数指针的值是什么意思

c - 如何在没有警告的情况下处理这些 typedef?

c++ - 如何以正确的方式构建 CMakeLists?

c - 在 mmap 中执行代码以产生可执行代码段错误

c++ - C++ Linux 应用程序的内存可视化

c++ - auto_ptr 和 dynamic_pointer_cast

c++ - 使用cUrl时如何修复丢失的libsasl.dll?