码迷,mamicode.com
首页 > 其他好文 > 详细

函数指针的应用

时间:2017-08-18 12:35:08      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:返回   hello   cout   out   amp   内容   using   应用   种类型   

#include <iostream>
#include <string>
using namespace std;

void print()
{
    cout << "hello world" << endl;
}

int max(int num1,int num2)
{
    return num1>num2?num1:num2;
}

//(二)使用typedef更直观更方便。
//形式2:typedef 返回类型(*新类型)(参数表)
typedef int (*PFUN_t) (int,int);    //定义了一种新的类型,并定义这种类型为指向函数的指针

//函数指针作为参数,并在函数内执行函数
void  excu_pfun(PFUN_t t_pfun,int num1,int num2)
{
    cout << (*t_pfun) (num1,num2) << endl;  //out:max
}

int main()
{
//(一)简单的函数指针的应用。
//形式1:返回类型(*函数名)(参数表)
//例如: int (*pfun) (in,int);

    void (*pfun) () = NULL; //定义了一个void函数指针,初始指向NULL
    pfun = print;   //print函数名就是该函数的地址,将该函数地址赋给pfun函数指针
    (*pfun) (); //也是用*取出函数指针指向的内容,执行函数print()

    int (*pfun1) (int,int);    //定义一个int函数指针,不初始化
    pfun1 = max;    //第一种赋值方式,使用函数名赋值:函数指针pfun1指向max函数
    //pfun1 = &max; //第二种赋值方式,使用函数的地址赋值,本质2种方法一样
    cout << (*pfun1) (2,3) << endl; //out: 3

    PFUN_t  pfun2;  //使用新的函数指针类型,定义函数指针pfun2
    pfun2 = max;    //赋值:函数指针pfun2指向max函数
    cout << (*pfun2) (4,5) << endl; //out: 5

    //max函数指针作为参数,并在函数内执行max函数
    excu_pfun(max,6,7); //out:7
}

 

函数指针的应用

标签:返回   hello   cout   out   amp   内容   using   应用   种类型   

原文地址:http://www.cnblogs.com/linuxAndMcu/p/7388893.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!