函数指针
(1)函数指针指的是函数而非对象。
(2)要想声明一个指向函数的指针,只要用指针替换函数名即可:
bool lengthcompare(const string&,const string&);
bool (*pf)(const string&,const string&);(此处声明了一个函数指针)
下面为函数指针赋值:有以下两种等价方法
pf=lengthcompare;
pf=&lengthcompare;
下面是三个等价调用:
bool b1=pf(“hello”,”goodbay”);
bool b2=(*pf)(“hello”,”goodbay”);
bool b3=lengthcompare(“hello”,”goodbay”);
(3)在指向不同函数类型(返回类型,形参类型)的指针之间不存在转换规则。
(4)函数指针与形参
和数组类似,虽然不能定义函数类型的形参,但是形参可以是指向函数的指针。
void usebigger(const string &s1,const string &s2,
bool pf(const string &,const string&));
void usebigger(const string &s1,const string &s2,
bool (*pf)(const string &,const string&));
void usebigger(const string &s1,const string &s2,
lengthcompare);
(5)返回指向函数的指针
和数组类似,虽然我们不能返回一个函数,但是可以返回指向函数的指针。然而我们必须把返回类型写成指针的形式,编译器不会为我们自动将函数返回类型当做指针来处理
例如,下面是个返回类型:
int (*f1(int)) (int *, int );//声明一个返回函数指针的函数
f1有形参说明f1是函数;f1前有*说明f1返回一个指针;进一步发现指针的类型本身也有形参列表,因此指针指向了函数,该函数返回类型是int,形参是(int*,int)。
即f1函数返回一个类型是int(int*,int)的指针。
尾置返回类型:auto f1(int)->int (*)(int* ,int) ;