小言_互联网的博客

C++ 函数指针

318人阅读  评论(0)

摘要

C++ 函数指针,
函数指针形参,
函数指针作为返回值。


一句话笔记

函数指针要想指向一个函数函数,要求它们的形参形式和返回值类型完全相同。

bool lengthCompare(const string &, const string &);
// pf指向一个函数,该函数参数为(const string &, const string &),返回值为bool类型
bool (*pf)(const string &, const string &);	//未初始化

// 使用函数指针
pf = lengthCompare;		// pf指向名为lengthCompare的函数
pf = &lengthCompare;	// pf指向名为lengthCompare的函数,与上一句等价

bool b1 = lengthCompare("hello", "goodbye");	//调用lengthCompare的函数
bool b2 = pf("hello", "goodbye");				//调用lengthCompare的函数,与上一句等价
bool b3 = (*pf)("hello", "goodbye");			//调用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 &));

// 利用typedef 和 decltype简化使用函数指针的代码
// 注意:decltype(lengthCompare)返回的是lengthCompare函数类型,我们需要加*以表明
// 我们的函数是返回该类型的指针,而非函数本身。
// Func和Func2是函数类型别名
typedef bool Func(const string &, const string &);
typedef decltype(lengthCompare) Func2;		//与上一句等价的类型
// FuncP和FuncP2是函数指针类型别名
typedef bool (*FuncP)(const string &, const string &);
typedef decltype(lengthCompare) *FuncP2;	//与上一句等价的类型
// 使用类型别名的等价声明如下
void useBigger(const string &s1, const string &s2, Func);//编译器自动把Func变为指针
void useBigger(const string &s1, const string &s2, FuncP2);

// 返回指向函数的指针
using F = int(int*, int);		// F是函数类型,不是函数指针类型
using PF = int(*)(int*, int);	//PF是函数指针类型
//使用以上类型别名声明函数返回值
F f1(int);	// 错误:F是函数类型,而函数的返回值不能是函数
F *f1(int);	// 正确:函数的返回值可以是函数指针
PF f1(int);	// 正确。
int (*f1(int))(int*, int); 			// 我们也能直接声明f1,与上一句等价
auto f1(int) -> int (*)(int*, int);	// 使用尾置返回类型(trailing return type)的方式,与上一句等价

相关知识点

  • using
  • typedef
  • decltype

相关/参考链接

《C++ prime 第五版》p221-223


转载:https://blog.csdn.net/a435262767/article/details/101236732
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场