函数指针

本文围绕C++函数指针展开,介绍其指向函数的特性,函数类型由返回值和形参类型决定。阐述了函数指针的声明、初始化、使用方法,强调赋值时函数类型与指针类型需精确匹配。还提及使用类型别名简化声明,以及在函数参数和返回值中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

函数指针

函数指针指向函数而非普通变量。和其他指针一样,函数指针指向某种特定的类型。(函数的类型由它的***返回值***和***形参类型***共同决定,如:bool func(const string& x, const string& y),该函数的类型是bool(const string&, const string&)。 )

声明一个指向函数的指针
//原函数
bool lengthCompare(const string&, const string&);
//pf指向一个函数,该函数的参数是两个const string的引用,返回值是bool类型
bool (*pf) (const string &, const string &);
注意:

  1. 指针pf未初始化,可以将pf初始化为空指针:pf = 0;
  2. pf两端的括号必不可少。如果省略,则:
    //声明一个名为pf的函数,该函数返回bool
    bool *pf(const string &, const string &);

使用函数指针
//pf指向名为lengthCompare的函数
pf = lengthCompare;
//使用指针调用该函数,由于函数名是指向该函数的指针,无需提前解引用
bool b1 = pf(“hello”, “goodbye”);
C++也同时支持使用取地址符合解引用操作符的版本,这种看起来更像是指针操作:
//将lengthCompare函数的地址赋给pf
pf = &lengthCompare;
//使用指针调用该函数
bool b2 = (*pf) (“hello”, “goodbye”);

注意: 向函数指针赋值时,函数类型与指针类型需精确匹配。如:bool cstringCompare(const char*, const char*); 我们不能将cstringCompare赋给pf。

使用类型别名进行简化
//Func是函数类型
typedef bool Func(const string&, const string&);
typedef decltype(lengthCompare) Func;
//FuncP是指向函数的指针
typedef bool (*FuncP) (const string&, const string&);
typedef decltype(lengthCompare) * FuncP;

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

使用typedef关键字或using声明进行简化,这在声明有函数指针类型参数的函数或返回指向函数的指针的函数时很有用。
如:
void useBigger(const string&,const string&, Func);
//等价声明 void useBigger(const string &,const string &, bool pf(const string &, const string &)); >注意:虽然第三个参数是函数类型,它会自动转换为指向函数的指针(我们不能传递函数类型的参数)
void useBigger(const string &, const string &, FuncP);
//等价声明void useBigger(const string &, const string &, bool (*pf) (const string &, const string &));

PF f1(int); //正确:返回指向函数的指针
F f1(int); //错误:F是函数类型,不能返回一个函数
F * f1(int); //正确:显示地指定返回类型是指向函数的指针
//等价声明:int (*f1(int)) (int *, int);

参考:
《C++ Primer》第5版

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值