【发布时间】: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;
}
x 和 y 如何从 yetAnotherFuncOutput 变为 yetAnotherFunc?
或者换个方式问:没有typedef会是什么样子?
【问题讨论】:
-
它们被称为“函数指针”,而不是指针函数。 TBH 他们确实是一个主要的痛苦。它们存在于 C++ 中是因为它们直接映射到 CPU 指令,但有经验的 C++ 程序员通常更喜欢虚函数或
std::function。 -
Pre C++11 函数指针是出了名的简洁且难以阅读。您最好使用现代库实用程序,如 例如、
using myfunc_ptr_t = std::add_pointer_t<int(int, int)>.
标签: c++ function-pointers typedef