普通的函数指针

函数指针指向的是函数。和其他的指针一样,函数指针指向某种函数类型,函数的类型由函数的返回类型和形参类型决定,与函数名无关

例如:

//一个比较string长度大小的函数
bool stringLengthCompare(const string& left, const string& right);
//这个函数的类型是bool (const string& left, const string& right);

int main()
{
    //一个指向这种类型的函数指针
    bool (*pf)(const string& left, const string& right);//没有初始化可以初始化返回0或者nullptr
    //*pf两边的括号不能少,少了就不是函数指针了
    //而是一个返回bool*的函数了 bool *pf(const string& left, const string& right)

    string left("1234");
    string right("123456");
    //函数指针的使用
    pf = stringLengthCompare;//函数名就是函数的地址或者 pf = &stringLengthCompare;
    bool res = stringLengthCompare(left, right);
    res = pf(left, right);//res = (*pf)(left, right);

    return 0;
}

bool stringLengthCompare(const string& left, const string& right)
{
    return left.size() > right.size();
}


关于重载函数的指针

void ff(int);

void ff(double);

int main()
{
    //编译器通过指针类型决定选取哪一个ff函数,使函数指针和ff函数精确匹配
    void (*pf)(int) = ff;
    void (*pf1)(double) = ff;

    return 0;
}


函数指针作为形式参数

bool stringLengthCompare(const string& left, const string& right)
{
    return left.size() > right.size();
}

//第三个参数是函数类型,它会自动的转换成指向函数的指针
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&));

int main()
{
    string s1("sfw");
    string s2("1234");
    useBigger(s1, s2, stringLengthCompare);

    return 0;
}


为了避免函数指针在使用时显得太繁琐,可以使用类型别名或者decltype来简化使用
//对于函数类型
typedef bool Func(const string&, const string&);
typedef decltype(stringLengthCompare) Func1;

//对于函数指针类型
typedef bool(*pFunc)(const string&, const string&);
typedef decltype(stringLengthCompare) *pFunc1;

//使用简化后的函数指针来重新声明useBigger
void useBigger(const string& s1, const string& s2, Func pf);
void useBigger(const string& s1, const string& s2, Func1 pf);

void useBigger(const string& s1, const string& s2, pFunc pf);
void useBigger(const string& s1, const string& s2, pFunc1 pf);

int main()
{
    string s1("sfw");
    string s2("1234");
    useBigger(s1, s2, stringLengthCompare);
    


    return 0;
}

函数虽然不能作为一个返回值,但是指向函数的指针却可以

//当函数指针作为返回值使用时

int sumLength(int*, int);

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

PF f1(int);

F* f2(int);

F f3(int);//这个声明是错误的,不能返回一个函数

//当然也可以这样子声明一个f1,很繁琐
int (*f1(int))(int*, int);

//C++11中可以使用auto和decltype来简化上面的声明

//使用auto
auto f1(int) -> int(*)(int*, int);//尾置声明

//使用decltype,使用decltype的时候,返回的是一个函数类型,而不是函数指针,需要显式的加上*
decltype(sumLength) * getFunc(int);

函数指针当然也可以作为谓词传递到泛型算法中,这个后面再写

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值