函数指针
记录
#include <iostream> using namespace std; int add(int a,int b) { return a+b; } int mul(int a,int b) { return a*b; } typedef int(* type_pfun) (int,int);//type_pfun 是某种函数指针 数据类型. type_pfun getfun(int type) { if(type==1) { return &add; } else { return &mul; } } int main() { int(*tprocess) (int ,int);//tprocess是某种函数指针变量 tprocess=&add; cout<<tprocess(1,3)<<endl; tprocess=&mul; cout<<tprocess(1,3)<<endl; cout<<getfun(1)(1,3)<<endl; cout<<getfun(2)(1,3)<<endl; return 0; }
1)适合场景
编写基本库。需要执行某个方法。但是方法却是由使用库的程序员来编写。这个时候就很适合使用函数指针了。

浙公网安备 33010602011771号