我是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
?
让我们从 typedef int(*t_yetAnotherFunc)(int,int)
t_yetAnotherFunc
是可以指向一个方法的类型,该方法接受两个int
s作为参数并且返回一个值int
。
t_yetAnotherFunc doMoreMath(char op)
方法返回add
或subtract
基于char op
。这里add
和subtract
返回语句必须被视为那些方法的地址,而不是函数调用。
t_yetAnotherFunc yetAnotherFuncc = doMoreMath('+');
按照t_yetAnotherFunc
现在的定义,yetAnotherFuncc
可以做成点add
方法。
如果您需要使用其指针(此处)调用add
具有参数的函数(此处),则需要通过其指针提供其参数。这是通过以下行完成的。(int x, int y)
yetAnotherFuncc
yetAnotherFuncc(x, y)
int yetAnotherFuncOutput = yetAnotherFunc(x,y);
它add
使用参数x
(2)和y
(22)调用该函数,并且返回值add
存储在中yetAnotherFuncOutput
。
没有typedef
它,将是一个复杂的定义,如下所示
int(*doMoreMath(char op))(int, int) {
if(op == '+')
return add
else if(op == '-')
return subtract;
}
int(*yetAnotherFunc)(int, int) = doMoreMath('+');
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句