結(jié)構(gòu)體是由一系列具有相同類型或不同類型的數(shù)據(jù)構(gòu)成的數(shù)據(jù)集合。所以,標(biāo)準(zhǔn)C中的結(jié)構(gòu)體是不允許包含成員函數(shù)的,當(dāng)然C++中的結(jié)構(gòu)體對此進行了擴展。那么,我們在C語言的結(jié)構(gòu)體中,只能通過定義函數(shù)指針的方式,用函數(shù)指針指向相應(yīng)函數(shù),以此達到調(diào)用函數(shù)的目的。
函數(shù)指針
函數(shù)類型 (*指針變量名)(形參列表);第一個括號一定不能少。
“函數(shù)類型”說明函數(shù)的返回類型,由于“()”的優(yōu)先級高于“*”,所以指針變量名外的括號必不可少。
注意指針函數(shù)與函數(shù)指針表示方法的不同,千萬不要混淆。最簡單的辨別方式就是看函數(shù)名前面的指針*號有沒有被括號()包含,如果被包含就是函數(shù)指針,反之則是指針函數(shù)。
要聲明一個函數(shù)指針,使用下面的語法:
Return Type ( * function pointer's variable name ) ( parameters )
例如聲明一個名為func的函數(shù)指針,接收兩個整型參數(shù)并且返回一個整型值
int (*func)(int a , int b ) ;
可以方便的使用類型定義運用于函數(shù)指針:
typedef int (*func)(int a , int b ) ;
結(jié)構(gòu)體中的函數(shù)指針
我們首先定義一個名為Operation的函數(shù)指針:
typedef int (*Operation)(int a , int b );
再定義一個簡單的名為STR的結(jié)構(gòu)體
typedef struct _str { int result ; // 用來存儲結(jié)果 Operation opt; // 函數(shù)指針 } STR;
現(xiàn)在來定義兩個函數(shù):Add和Multi:
//a和b相加int Add (int a, int b){ return a + b ;}//a和b相乘int Multi (int a, int b){ return a * b ;}
現(xiàn)在我們可以寫main函數(shù),并且將函數(shù)指針指向正確的函數(shù):
int main (int argc , char **argv){ STR str_obj; str_obj.opt = Add; //函數(shù)指針變量指向Add函數(shù) str_obj. result = str_obj.opt(5,3); printf (" the result is %d/n", str_obj.result ); str_obj.opt= Multi; //函數(shù)指針變量指向Multi函數(shù) str_obj. result = str_obj.opt(5,3); printf (" the result is %d/n", str_obj.result ); return 0 ;}
運行結(jié)果如下:
the result is 8 the result is 15
完整的代碼如下:
#include<stdio.h>typedef int (*Operation)(int a, int b);typedef struct _str { int result ; // to sotre the resut Operation opt; // funtion pointer } STR;//a和b相加int Add (int a, int b){ return a + b ;}//a和b相乘int Multi (int a, int b){ return a * b ;}int main (int argc , char **argv){ STR str_obj; str_obj.opt = Add; //函數(shù)指針變量指向Add函數(shù) str_obj. result = str_obj.opt(5,3); printf ("the result is %d/n", str_obj.result ); str_obj.opt= Multi; //函數(shù)指針變量指向Multi函數(shù) str_obj. result = str_obj.opt(5,3); printf ("the result is %d/n", str_obj.result ); return 0 ;}
新聞熱點
疑難解答
圖片精選