c/288752.html">函數指針
函數存放在內存的代碼區域內,它們同樣有地址。如果我們有一個int test(int a)的函數,那么,它的地址就是函數的名字,如同數組的名字就是數組的起始地址。
1、函數指針的定義方式:data_types (*func_pointer)( data_types arg1, data_types arg2, ...,data_types argn);
c語言函數指針的定義形式:返回類型 (*函數指針名稱)(參數類型,參數類型,參數類型,…);
c++函數指針的定義形式:返回類型 (類名稱::*函數成員名稱)(參數類型,參數類型,參數類型,….);
例如: int (*fp)(int a); //這里就定義了一個指向函數(這個函數參數僅僅為一個int類型,函數返回值是int類型)的指針fp。
類成員函數指針與普通函數指針不是一碼事。前者要用.*與->*運算符來使用,而后者可以用*運算符(稱為“解引用”dereference,或稱“間址”indirection)。
普通函數指針實際上保存的是函數體的開始地址,因此也稱“代碼指針”,以區別于C/C++最常用的數據指針。
而類成員函數指針就不僅僅是類成員函數的內存起始地址,還需要能解決因為C++的多重繼承、虛繼承而帶來的類實例地址的調整問題,所以類成員函數指針在調用的時候一定要傳入類實例對象。
函數指針示例
#include <stdio.h>#include <stdlib.h>int fun1(){ printf("this is fun1 call/n"); return 1;}void fun2(int k, char c){ printf("this is fun2 call:%d %c/n", k, c);}int main(){ int (*pfun1)() = NULL; void (*pfun2)(int, char) = NULL; int a,b; pfun1 = fun1; //第一種賦值方法 a = pfun1(); //第一種調用方法(推薦) printf("%d/n",a); b = (*pfun1)();//第二種調用方法 printf("%d/n",b); pfun2 = &fun2;//第二種賦值方法(推薦,因為和其他數據指針賦值方法一致) pfun2(1,'a'); (*pfun2)(2,'b'); return 0;}
函數指針作為函數參數:
#include <stdio.h>#include <stdlib.h>void fun(int k, char c){ printf("this is fun2 call:%d %c/n", k, c);}void fun1(void (*pfun)(int, char), int a, char c){ pfun(a, c);}int main(){ fun1(fun, 1, 'a'); return 0;}// c++ 的形式差不多
函數指針作為函數返回值:
// c 形式#include <stdio.h>#include <stdlib.h>void fun(int k, char c){ printf("this is fun2 call:%d %c/n", k, c);}//fun1 函數的參數為double,返回值為函數指針void(*)(int, char)void (*fun1(double d))(int, char){ printf("%f/n",d); return fun;}int main(){ void (*p)(int, char) = fun1(3.33); p(1, 'a'); return 0;}//c++ 形式#include <iostream>using namespace std;class test{public: int fun(int a, char c) { cout<<"this is fun call:"<<a<<" "<<c<<endl; return a; }};class test2{ public: // test2 的成員函數fun1,參數是double, //返回值是test的成員函數指針int(test::*)(int, char) int (test::*fun1(double d))(int, char) { cout<<d<<endl; return &test::fun; }};int main(){ test mytest; test2 mytest2; int (test::*p)(int, char) = mytest2.fun1(3.33); (mytest.*p)(1, 'a'); return 0;}
函數指針數組:
#include <stdio.h>#include <stdlib.h>float add(float a,float b){return a+b;}float minu(float a,float b){return a-b;}int main(){ //定義一個函數指針數組,大小為2 //里面存放float (*)(float, float)類型的指針 float (*pfunArry[2])(float, float) = {&add, &minu}; double k = pfunArry[0](3.33,2.22);// 調用 printf("%f/n", k); k = pfunArry[1](3.33,2.22); printf("%f/n", k); return 0;}//c++ 可類比
typedef 簡化函數指針類型:
#include <stdio.h>#include <stdlib.h>float add(float a,float b){ printf("%f/n",a+b); return a+b;}float minu(float a,float b){ printf("%f/n",a-b); return a-b;}//用pfunType 來表示float(*)(float, float)typedef float(*pfunType)(float, float);int main(){ pfunType p = &add;//定義函數指針變量 p(3.33, 2.22); pfunType parry[2] = {&add, &minu};//定義函數指針數組 parry[1](3.33, 2.22); //函數指針作為參數可以定義為:void fun(pfunType p) //函數指針作為返回值可以定義為:pfunType fun(); return 0;}//c++ 可類比
總結
以上就是本文關于C++中函數指針詳解及代碼示例的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站:C語言實現的學生選課系統代碼分享等,有什么問題可以隨時留言,小編會及時回復大家的。
新聞熱點
疑難解答