C++学习——函数指针

一、函数指针的定义:指向函数的指针
二、函数指针的用途:1.调用函数; 2.做函数的参数。
(说明:系统会为一个定义好的函数分配内存,存储空间的首地址即函数的地址,用指针指向)
三、用法
1.区分传递的是函数地址还是函数的返回值
例如think是一个函数,process(think)使得process函数内部可以调用think函数,而process(think())是将think的返回值作为process的参数
2.声明函数指针
1.假设有一个普通的函数声明: double pam(int);
2.声明一个函数指针: double (*pf) (int);
pam是函数,所有(*pf)也是函数,pf就是函数指针
说明:这里的括号很重要,double (*pf) (int)表明pf是一个指向函数(函数的返回值是double)的指针,doubule *pf (int)表明pf是一个返回指针(指针指向double)的函数
3.声明函数指针之后就可以把函数的地址赋给它: pf=pam;
4.使用指针调用函数
四、示例
1.使用函数指针

//c++11
#include<stdio.h>
int min(int x,int y){return (x>y? y:x);}
int main()
{
    int (*ptr)(int, int);
    int a, b, c;
    ptr = min;
    //或者ptr=&min; 函数名作为值使用时,函数自动转换为指针 
    scanf("%d,%d", &a, &b);
    c = (*ptr)(a,b);
    //或者c = (*ptr)(a,b);*号可以去掉,直接使用指向函数的指针调用该函数,无需提前解引用指针:
    printf("min=%d", c);
    return 0;
}

2.函数指针作为形参

#include<stdio.h>
int Max(int a,int b);
int Min(int a,int b);
int Sum(int a,int b);
void fun(int a,int b,int(*p)(int,int));

void fun(int x,int y,int(*p)(int,int))//void fun(int x,int y,int p(int,int))
{
    int result;
    result=(*p)(x,y);
    printf("%d\n",result);
}
int Max(int x,int y)
{
    int z;
    if(x>y)
        z=x;
    else
        z=y;
    printf("max=");
    return z;
}
int Min(int x,int y)
{
    int z;
    if(x<y)
        z=x;
    else
        z=y;
    printf("min=");
    return z;
}

int main(void)
{
    int a,b;
    int n=0;
    printf("输入两个整数:\n");
    scanf("%d %d",&a,&b);
    printf("请用数字选择要进行的运算:1求最大,2求最小,\n");
    scanf("%d",&n);
    if(n==1)
        fun(a,b,Max);
    else if(n==2)
        fun(a,b,Min);
    else
        printf("输入选择有误!\n");
    return 0;
}

3.typedef等简化书写函数指针

#include <iostream>
using namespace std;
bool length_compare(const string &, const string &){}
// gel1 和 gel2 是等价的函数类型
typedef bool gel1(const string &, const string &);
typedef decltype(length_compare) gel2;

//gel3 和 gel4 是等价的指针类型
typedef bool(*gel3)(const string &, const string &);
typedef decltype(length_compare) *gel4;
//注意这里的 decltype 返回的是函数类型,此时不会将函数类型自动转换成指针类型,只有在 decltype 返回结果前加上 * 才能得到指针
void max(const string &s1, const string &s2, gel1){}//编译器自动将gel1转换成指针类型了
// void max(const string &s1, const string &s2, gel3){}//等价声明
int main(void){
    max("fjs", "jfls", length_compare);//把函数当作为实参使用,此时它会自动地转换成指针
    return 0;
}

4.返回指向函数的指针

#include<iostream>
using namespace std;
using F = int(*)(int);//F是指针类型
//使用类型别名来声明一个返回函数指针的函数
int a(int m){return m;}
F f1(){return a;}
int main()
{
    cout << "function a(10) vaule is: " << a(10) << endl;
    cout << "function f1()(5) vaule is: " << f1()(5) << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值