参见<<c++ primer>> p237页
bool (*pf)(const string &, const string &);
typedef bool (*cmpFcn) (const string &,const string &);//表示cmpFcn是一种指向函数的指针类型的名字
bool lengthCompare(const string &,const string &){return 0;}
int main()
{
cmpFcn pf1 = 0;//函数指针初始化为0表示该指针不指向任何函数
cmpFcn pf2 = lengthCompare;
pf2 = pf1;
pf1 = lengthCompare;
pf2 = &lengthCompare;//在函数名上应用取地址操作符 等效于 直接引用函数名
lengthCompare("hi","bye");
(*pf2)("hi","bye");
pf1("hi","bye");//可以不需要使用解引用操作符,直接通过指针调用函数
return 0;
}
void useBigger1(const string &,const string &,bool(const string&,const string&) );//函数指针作形参的两种形式
void useBigger2(const string &,const string &,bool (*)(const string&,const string&) );
本文介绍了C++中函数指针的基本概念及使用方法,包括如何定义和初始化函数指针,以及如何通过函数指针来调用函数。此外,还展示了函数指针作为参数传递给其他函数的例子。
2万+

被折叠的 条评论
为什么被折叠?



