C++函数指针

定义

函数指针指向的是一个函数而非一个对象,函数指针的类型由它的返回值和形参类型共同决定,与函数名无关。(函数名只是个名称)

例如

bool iscompare(const string &);

此函数的类型为

bool (const string&)

指向该函数的函数指针声明为:

bool (*ptr)(const string&);

注意!
上侧函数指针的声明中,pf前面有个*号,表示pf是指针;pf右侧是形参列表,表示of指向的是函数;左侧函数的返回值类型是bool值,说明该函数的返回值是bool;总结下:pf是一个指向函数的指针,参数如形参列表所示,返回值是bool类型

如果bool (*ptr)(const string&); 写成了 bool *ptr(const string&); 就表示为了返回值是bool指针的函数

bool *pf(const string&);//声明一个名为pf的函数,返回值类型为bool*

函数指针的使用

当我们将函数名当做值来使用,函数名自动转为指针

pf = iscompare;
pf = &iscompare;
//二者效果一样
//三者的作用是一样的
bool b1 = pf("hello");
bool b2 = (*pf)("hello");
bool b3 = iscompare("hello");

当给函数指针赋一个nullptr或者0时,表示该指针没有指向任何函数。


函数指针形参

形参可以是指向函数的指针:

//对于上面的情况,假如我们在另一个函数中用这个函数指针作为形参

void test(const string&,bool pf(const string&));
void test(const string&,bool (*pf)(const string&));

使用的时候可以这样

test(str1,pf);
test(str1,(*pf));
test(str1,iscompare);//直接把函数名作为实参使用,它会自动转换成指针

你可能感兴趣的:(c++,c++)