c++學習筆記-----函數指針

通過typedef來簡化函數指針


typedef int (*FUN)(int a,int b);      //聲明FUN是一個函數指針類型

Fun funp;         //funp爲一個返回整型和兩個整數形參的函數指針




#include<iostream>
#include<malloc.h>
#include<mem.h>
#include<math.h>
using namespace std;


double sigma(double (*func)(double),double d1,double d2)
{
    double dt = 0.0;
    for(double d = d1;d < d2;d += 0.1)
    {
        dt += func(d);
    }
    return dt;
}
int main()
{
    double dsum;
    dsum = sigma(sin,0.1,1);
    cout<<"the sum of sin from 0.1 to 1 is "<<dsum<<endl;
    dsum = sigma(cos,0.5,3.0);
    cout<<"the sum of cos from 0.5 to 3.0 is"<<dsum<<endl;






    return 0;
}



函數指針可以構成指針數組
源代碼示例:

#include<iostream>
#include<stdlib.h>
using namespace std;




typedef void (*MenuFun)();
void f1(){cout<<"good"<<endl;}
void f2(){cout<<"better"<<endl;}
void f3(){cout<<"best"<<endl;}
MenuFun fun[] = {f1,f2,f3};


int main()
{
    cout<<"1----->display good"<<endl;
    cout<<"2----->display better"<<endl;
    cout<<"3----->display best"<<endl;
    cout<<"enter your choice"<<endl;
    int choice;
    cin>>choice;
    switch(choice)
    {
    case 1:
        fun[0]();
        break;
    case 2:
        fun[1]();
        break;
    case 3:
        fun[2]();
        break;


    }
    return 0;
}









發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章