我是 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;
}
x
和 y
如何从 yetAnotherFuncOutput
到 yetAnotherFunc
?
或者另一种提问方式:如果没有 typedef
,这会是什么样子?
最佳答案
指向函数的指针可以像任何其他函数一样使用,当您调用它时,您会像调用任何其他函数一样得到结果。它就像是另一个函数的别名。
在您的情况下,您为 add
函数创建了一个别名,当您调用 yetAnotherFunc
时,您实际上是在调用 add
。
声明
int yetAnotherFuncOutput= yetAnotherFunc(x,y);
相当于
int yetAnotherFuncOutput= add(x,y);
关于c++ - 编写此指针函数代码的长格式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34987049/