函数指针

/*
	时间: 2018/11/12
	书籍: c++ primer 第五版  部分c++11标准
*
函数指针

顾名思义

  1. 如何定义一个函数指针?

    把函数名换成指针即可

    int minus(int a,int b);
    
    int (*pf_minus)(int,int);//指向含有两个int形参返回值为int的函数
    
  2. 如何用typedef来表示

    //表示pf_minus就是指向含有两个int形参返回值为int函数的命名
    typedef int (*pf_minus)(int,int);
    
    int minus(int a,int b);
    
  3. 如何定义函数形参

    常见如qsort函数实现的compare函数就是一个函数指针

    //定义一个含有函数形参的函数
    int commps(int a,int b,int (*comp)(const void*,const void* b));
    
    //写一个comp,如果传入为int a[100]
    int comp(const void* a,const void* b)
    {
        return *(int*)a - *(int*)b;
    }
    
    //调用commps函数
    commps(2,2,comp);
    
//pointer_func.cpp
#include <iostream>
#include <vector>

int minus(int a,int b)
{
	return a - b;
}

int devid(int a,int b)
{
	return a / b;
}

int add(int a,int b)
{
	return a + b;
}

int mul(int a,int b)
{
	return a * b;
}

typedef int (*pf)(int,int) ;

typedef int f(int,int);

int main()
{
	std::vector<pf> pf_vec;//定义函数指针向量

	pf_vec.push_back(minus);	
	pf_vec.push_back(devid);
	pf_vec.push_back(add);
	pf_vec.push_back(mul);

	std::vector<pf>::iterator it_pf = pf_vec.begin(); //定义迭代器初始化

	std::vector<pf>::size_type index_pf = 0; //定义下标

	while(it_pf != pf_vec.end())
	{
		std::cout << (*it_pf)(100,100) <<std::endl;
		std::cout << (pf_vec[index_pf])(100,100) <<std::endl;
		it_pf++;
		index_pf++;
	}

	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值