【问题标题】:What is the longform way of writing this pointer function code?编写此指针功能代码的长格式方法是什么?
【发布时间】:2016-01-25 07:18:30
【问题描述】:

我是 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会是什么样子?

【问题讨论】:

  • 它们被称为“函数指针”,而不是指针函数。 TBH 他们确实是一个主要的痛苦。它们存在于 C++ 中是因为它们直接映射到 CPU 指令,但有经验的 C++ 程序员通常更喜欢虚函数或std::function
  • Pre C++11 函数指针是出了名的简洁且难以阅读。您最好使用现代库实用程序,如 例如using myfunc_ptr_t = std::add_pointer_t&lt;int(int, int)&gt;.

标签: c++ function-pointers typedef


【解决方案1】:

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

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

声明

int yetAnotherFuncOutput=           yetAnotherFunc(x,y);

等价于

int yetAnotherFuncOutput=           add(x,y);

【讨论】:

    【解决方案2】:

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

    t_yetAnotherFunc 是可以指向一个方法的类型,该方法接受两个ints 作为参数并返回一个int

    t_yetAnotherFunc doMoreMath(char op) 方法根据char op 返回addsubtract。这里的addsubtract 在return 语句中必须被视为这些方法的地址而不是函数调用。

    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) 调用函数addadd 的返回值存储在yetAnotherFuncOutput 中。

    如果没有typedef,它将是一个复杂的定义,如下所示

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

    【讨论】:

      猜你喜欢
      • 2010-11-22
      • 2020-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-14
      相关资源
      最近更新 更多