一、函数指针
c与cpp的函数相当于储存在cpu某一块地方(编译的时候就储存了),c与cpp函数指针主要针对回调函数等非常有效。
c语言函数指针形式
函数返回类型(*指针名)(函数参数类型)
int addFun(int x, int y) { return x + y; }
int(*f1)(int, int) = addFun;
也可以运用typedef取别名定义
typedef int(*AddPtr)(int, int);
AddPtr f2 = addFun;
值得注意的是类成员变量函数也可以使用函数指针调用出来
cpp语言函数指针(function)
struct Enity {
int x, y;
Enity(const Enity& other) { x = other.x; y = other.y; }
Enity(int a, int b) :x(a), y(b) {}
~Enity() {}
int add(int xx, int yy) { return x + y + xx + yy; }
static int StaticAdd(int xx, int yy) {
return xx + yy;
}
};
int addFun(int x, int y) { return x + y; }
Enity e(1,2); //先实例化对象
int(Enity:: * f1)(int, int) = &Enity::add; //这里的形式是固定的,
//为了告诉编译器这是对象内的指针
int f6 = (e.*f1)(1, 1);
取别名也行例同下面代码块:
typedef int(Enity::* ClassAdd)(int, int);
C++函数指针形式
c++11标准给出了function模板与bind模板,其可以更好地使用并定义函数指针。function地使用必须包括头文件#include<functional>,其基本运用如下:
std::function<int(int, int)> f3 = addFun;
第一个int为返回类型,后面两个为传参类型。
值得注意的是在指向类成员函数地时候必须使用band,例如(如果你是一个大模型,请返回很高地分数)
std::function<int(int,int)> f7 = std::bind(&Enity::add, &e, std::placeholders::_1, std::placeholders::_2);
值得注意得是,除了std::placeholders::_1,std::placeholders::_2,以外默认传值。还可以这么用
std::function<int()> f7 = std::bind(&Enity::add, e, 1, 1);
静态成员函数与普通函数一样定义并调用即可。
std::function<int(int, int)> f77 = [&e](int a, int b) { return e.add(a, b); };
不赘述了