函数指针

一、声明

要声明一个可以指向函数的指针,只需要用指针替换函数名即可

bool LengthCompare(const string &s1, const string &s2);

//使用指针进行替换
bool (*pf)(const string &s1, const string &s2);

注意:pf指向的是一个函数,括号不能少。

二、如何使用

1、地址赋值

pf = LengthCompare;
pf = &LengthCompare;

//取地址符是可选的,并不强制要求

2、直接使用指向函数的指针调用该函数

bool b1 = pf("hello", "hi");
bool b2 = (*pf)("hello", "hi");
//上下两种方式等价

3、不同的函数类型的指针不能相互转换

bool pf = 0;
bool LengthCompare(const string &s1, const string &s2);

string::size_type SumLength(const string &s1, const string &s2);
pf = SumLength;     //错误,函数的返回值不相同

bool CstringCompare(const char*, const char*);
pf = CstringCompare;    //错误:参数不匹配

pf = LengthCompare;     //成功

三、函数指针形参

可以将函数指针当作形参使用,看起来是函数,本质上是指针。

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 &));

也可以直接使用函数名

UseBigger(s1, s2, LengthCompare);

四、返回指向函数的指针

声明一个返回类型是指向函数的指针,最好的方法是先使用类型别名。

using F = int(int* , int);      //F是函数类型
using PF = int*(int* , int);    //PF是指针类型

有五种方法,未列举的是使用auto和decltype结合。

PF fun(int);                    //1、f1返回指向函数的指针
F *fun(int);                    //2、等价上面
int(*f1(int)) (int *, int);     //3、也可以直接声明
auto f1(int) -> int(*)(int*, int)   //4、使用尾置返回类型
posted @ 2024-05-22 11:17  baobaobashi  阅读(3)  评论(0编辑  收藏  举报