結構體中定義函式指標
結構體指標變數的定義,定義結構體變數的一般形式如下:
形式1:先定義結構體型別,再定義變數
struct結構體識別符號
{
成員變數列表;…
};
struct 結構體識別符號 *指標變數名;
變數初始化一:struct結構體識別符號 變數名={初始化值1,初始化值2,…, 初始化值n };
形式2:在定義型別的同時定義變數
struct結構體識別符號
{
成員變數列表;…
} *指標變數名;
變數初始化二:
形式3:直接定義變數,用無名結構體直接定義變數只能一次
struct
{
成員變數列表;…
}*指標變數名;
其中“指標變數名”為結構體指標變數的名稱。形式1是先定義結構體,然後再定義此型別的結構體指標變數;形式2和形式3是在定義結構體的同時定義此型別的結構體指標變數。
函式指標的定義
一般的函式指標可以這麼定義:
int(*func)(int,int);
表示一個指向含有兩個int引數並且返回值是int形式的任何一個函式指標. 假如存在這樣的一個函式:
int add2(int x,int y)
{
return x+y;
}
那麼在實際使用指標func時可以這樣實現:
func=&add2; //指標賦值,或者func=add2; add2與&add2意義相同
printf("func(3,4)=%d\n",func(3,4));
事實上,為了程式碼的移植考慮,一般使用typedef定義函式指標型別.
typedef int(*FUN)(int,int);
FUN func=&add2;
func();
結構體中包含函式指標
其實在結構體中,也可以像一般變數一樣,包含函式指標變數.下面是一種簡單的實現.
- #include <stdio.h>
- struct DEMO
- {
- int x,y;
- int (*func)(int,int); //函式指標
- };
- int add1(int x,int y)
- {
- return x*y;
- }
- int add2(int x,int y)
- {
- return x+y;
- }
- void main()
- {
- struct DEMO demo;
- demo.func=add2; //結構體函式指標賦值
- //demo.func=&add2; //結構體函式指標賦值
-
printf("func(3,4)=%d\n"
- demo.func=add1;
- printf("func(3,4)=%d\n",demo.func(3,4));
- }
- /*
- 輸出:
- func(3,4)=7
- func(3,4)=12
- */
結構體中指向函式的指標
C語言中的struct是最接近類的概念,但是在C語言的struct中只有成員,不能有函式,但是可以有指向函式的指標,這也就方便了我們使用函數了。舉個例子,如下:- #include <stdio.h>
-
#include <stdlib.h>
- #include <string.h>
- typedefstruct student
- {
- int id;
- char name[50];
- void (*initial)();
- void (*process)(int id, char *name);
- void (*destroy)();
- }stu;
- void initial()
- {
- printf("initialization...\n");
- }
- void process(int id, char *name)
- {
- printf("process...\n%d\t%s\n",id, name);
- }
- void destroy()
- {
- printf("destroy...\n");
- }
- int main()
- {
- stu *stu1;
- //在VC和TC下都需要malloc也可以正常執行,但是linux gcc下就會出錯,為段錯誤,必須malloc
- stu1=(stu *)malloc(sizeof(stu));
- //使用的時候必須要先初始化
- stu1->id=1000;
- strcpy(stu1->name,"C++");
- stu1->initial=initial;
- stu1->process=process;
- stu1->destroy=destroy;
- printf("%d\t%s\n",stu1->id,stu1->name);
- stu1->initial();
- stu1->process(stu1->id, stu1->name);
- stu1->destroy();
- free(stu1);
- return 0;
- }
輸出:
/*
1000 C++
initialization...
process...
1000 C++
destroy...
*/
C語言中,如何在結構體中實現函式的功能?把結構體做成和類相似,讓他的內部有屬性,也有方法
這樣的結構體一般稱為協議類,提供參考:
struct {
int funcid;
char *funcname;
int (*funcint)(); /* 函式指標 int 型別*/
void (*funcvoid)(); /* 函式指標 void型別*/
};
每次都需要初始化,比較麻煩
- #include <stdio.h>
- typedefstruct
- {
- int a;
- void (*pshow)(int);
- }TMP;
- void func(TMP *tmp)
- {
- if(tmp->a >10)//如果a>10,則執行回撥函式。
- {
- (tmp->pshow)(tmp->a);
- }
- }
- void show(int a)
- {
- printf("a的值是%d\n",a);
- }
- void main()
- {
- TMP test;
- test.a = 11;
- test.pshow = show;
- func(&test);
- }
- /*
- 一般回撥函式的用法為:
- 甲方進行結構體的定義(成員中包括回撥函式的指標)
- 乙方定義結構體變數,並向甲方註冊,
- 甲方收集N個乙方的註冊形成結構體連結串列,在某個特定時刻遍歷連結串列,進行回撥。
- 當 函式指標 做為函式的引數,傳遞給一個被呼叫函式,
- 被呼叫函式就可以通過這個指標呼叫外部的函式,這就形成了回撥<p>一般的程式中回撥函式作用不是非常明顯,可以不使用這種形式</p><p>最主要的用途就是當函式不處在同一個檔案當中,比如動態庫,要呼叫其他程式中的函式就只有採用回撥的形式
- 通過函式指標引數將外部函式地址傳入來實現呼叫</p><p>函式的程式碼作了修改,也不必改動庫的程式碼,就可以正常實現呼叫便於程式的維護和升級</p>*/