zoukankan      html  css  js  c++  java
  • C++ 函数指针(指向函数的指针)

    • 函数指针
      • 一个函数总是占用一段连续的内存区域,函数名在表达式中有时会被转换成该函数所在区域的首地址,这和数组名非常类似。
      • 我们可以把函数的这个首地址(或称入口地址)赋予一个指针变量,使指针变量指向函数所在的内存区域,然后通过指针变量就可以找到并调用该函数。

    函数的类型由它的返回类型和形参类型共同决定,与函数名无关。

    bool lengthCompare(const string &, const string &);
    //该函数的类型是bool (const string &, const string &)。
    bool (*pf) (const string &, const string &);
    //pf指向一个函数,该函数的参数是两个const string的引用,返回值是bool类型
    

    1. 使用函数指针

    当我们把函数名作为一个值使用时,该函数自动转换成指针。

    pf = lengthCompare; //pf指向名为lengthCompare的函数
    pf = &lengthCompare; //等价的赋值语句:取地址符是可选的
    

    使用函数指针调用函数:

    bool b1 = pf("hello", "goodbye");            //调用lengthCompare函数
    bool b2 = (*pf) ("hello", "goodbye");        //一个等价的调用
    bool b3 = lengthCompare("hello", "goodbye"); //另一个等价的调用
    

    我们可以为函数指针赋一个nullptr或者值为0的整型常量表达式,表示该指针没有指向任何一个函数。

    2. 函数指针形参

    虽然不能定义函数类型的形参,但是形参可以是指向函数的指针。此时,形参看起来是函数类型,实际上却是当成指针使用:

    //第三个形参是函数类型,它会自动转换成指向函数的指针
    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 &));
    //可以直接将函数作为实参使用,此时它会自动转换成指针
    useBigger(s1, s2, lengthCompare);
    

    3. 返回指向函数的指针

    和数组一样,虽然不能返回一个函数,但是能返回指向函数类型的指针。然而,我们必须把返回类型写成指针形式。
    想要声明一个返回函数指针的函数,最简单的方法是使用类型别名:

    using F = int(int *, int); //F是函数类型,不是指针
    using PF = int(*)(int *, int); //PF是指针类型
    PF f1(int); //正确:PF是指向函数的指针,f1返回指向函数的指针
    F f1(int);  //错误:F是函数类型,f1不能返回一个函数
    F *f1(int); //正确:显式的指定返回类型是指向函数的指针
    
  • 相关阅读:
    shell 基础进阶 *金字塔
    shell,awk两种方法写9*9乘法表
    shell脚本判断一个用户是否登录成功
    shell 冒泡算法 解决数组排序问题
    shell 石头剪刀布
    应用shell (ssh)远程链接主机
    nmcli命令使用
    光盘yum源autofs按需挂载
    LVM扩容,删除
    LVM创建
  • 原文地址:https://www.cnblogs.com/xiaobaizzz/p/12169375.html
Copyright © 2011-2022 走看看