函数指针

来源:互联网 发布:淘宝儿童文胸模特 编辑:程序博客网 时间:2024/06/08 16:30

一,指针函数

类型标识符   *函数名(参数表)

int *f(x,y);

首先它是一个函数,只不过这个函数的返回值是一个地址值。函数返回值必须用同类型的指针变量来接受,也就是说,指针函数一定有函数返回值,而且,在主调函数中,函数返回值必须赋给同类型的指针变量。

float *fun();

float *p;

p = fun();

二,函数指针

int* a;

 

类型标示符*指针变量名)(参数表)

int (*fun)(int a,int b);


一个函数的函数名,本身就是一个指向该函数的代码在内存中的首地址。

而fun_ptr是指向一个返回值为int,有两个int型参数的函数的指针。

注意一点:

函数指针和它指向的函数的参数个数和类型都应该是致的;

函数指针的类型和函数的返回值类型也必须是一致的。

三,使用typedef的函数指针。


使用了typedef,就表示将这个函数指针定义成了一种类型,然后可以用这种类型来定义函数指针。

四,指向类成员的函数指针

类型标示符(类名::*指针变量名)(参数表)

int (TMyClass::*pt2Member)(floatcharchar);

五,例子

下面是一个指向函数的指针使用的例子

#include <iostream.h>/*指向函数的指针*/typedef int (*pFun)(int, int);int Max(int a, int b){    return a > b ? a : b;}int Min(int a, int b){    return a < b ? a : b;}/*通用接口函数,实现对其他函数的封装*/int Result(pFun fun, int a, int b){    return (*fun)(a, b);}void main(){    int a = 3;    int b = 4;    cout<<"Test function pointer: "<<endl;    cout<<"The maximum number between a and b is "<<Result(Max, a, b)<<endl;    cout<<"The minimum number between a and b is "<<Result(Min, a, b)<<endl;}

下面是一个指向类的成员函数的指针的使用的例子,包括指向静态和非静态成员函数的指针的使用。

#include <iostream.h>        class CA;        /*指向类的非静态成员函数的指针*/    typedef int (CA::*pClassFun)(int, int);        /*指向一般函数的指针*/    typedef int (*pGeneralFun)(int, int);        class CA    {    public:            int Max(int a, int b)        {            return a > b ? a : b;        }                int Min(int a, int b)        {            return a < b ? a : b;        }            static int Sum(int a, int b)        {            return a + b;        }            /*类内部的接口函数,实现对类的非静态成员函数的封装*/        int Result(pClassFun fun, int a, int b)        {            return (this->*fun)(a, b);        }        };        /*类外部的接口函数,实现对类的非静态成员函数的封装*/    int Result(CA* pA, pClassFun fun, int a, int b)    {        return (pA->*fun)(a, b);    }        /*类外部的接口函数,实现对类的静态成员函数的封装*/    int GeneralResult(pGeneralFun fun, int a, int b)    {        return (*fun)(a, b);    }            void main()    {        CA ca;        int a = 3;        int b = 4;                cout<<"Test nonstatic member function pointer from member function:"<<endl;        cout<<"The maximum number between a and b is "<<ca.Result(CA::Max, a, b)<<endl;        cout<<"The minimum number between a and b is "<<ca.Result(CA::Min, a, b)<<endl;            cout<<endl;        cout<<"Test nonstatic member function pointer from external function:"<<endl;        cout<<"The maximum number between a and b is "<<Result(&ca, CA::Max, a, b)<<endl;        cout<<"The minimum number between a and b is "<<Result(&ca, CA::Min, a, b)<<endl;            cout<<endl;        cout<<"Test static member function pointer: "<<endl;        cout<<"The sum of a and b is "<<GeneralResult(CA::Sum, a, b)<<endl;    }

参考链接:http://www.cnblogs.com/xianyunhe/archive/2011/11/26/2264709.html



0 0