在C/C++中的struct使用函式指標,而且在C++中的struct還能使用成員函式
阿新 • • 發佈:2019-01-10
1、函式指標
一般的函式指標可以這麼定義:
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();
2、結構體中包含函式指標
其實在結構體中,也可以像一般變數一樣,包含函式指標變數.下面是一種簡單的實現.
#include "stdio.h"
struct DEMO
{
int x,y;
int (*func)(int,int); //函式指標
};
int add2(int x,int y)
{
return x+y;
}
void main()
{
struct DEMO demo;
demo.func =&add2; //結構體函式指標賦值
printf("func(3,4)=%d\n",demo.func(3,4));
}
上面的檔案儲存為mytest.c,在VC6.0和gcc4中編譯通過.
3、C++允許結構體中有成員函式
既然在C++中介紹類的時候說過“類是取代結構體的”。可見結構體的功能並非我們平時用到的這麼簡單,沒有太多人知道結構體中也可以有自己的函式成員。
也就是說,在C++中允許結構體包含函式成員,而標準C不支援。 進一步發現,c++中甚至允許結構體中含有建構函式、過載、public/private等等.這樣看來,結構體真的與類越來越靠近相似了!
C++擴充了結構體的功能。但C++中為了介紹面向物件的類,卻淡化了同樣精彩的結構體。當我們寫一些小程式而覺得沒有必要去構造類的時候,選擇結構體確實會方便很多。
舉個例子:
#include "stdio.h"
struct DEMO
{
int m;
DEMO(int k) //建構函式
{
this->m=k;
printf("after init,m=%d\n",m);
}
void func()//一般函式
{
printf("function of struct.\n");
}
};
void main()
{
struct DEMO demo(33);
demo.func();
}
儲存為mytest1.c , VC6.0和gcc編譯都會出錯。這可能說明標準C是不支援結構體包括函式成員形式的(因為字尾.c使得VC或gcc選擇c編譯器)。 但是如果將檔案字尾改為.cpp(也就是選擇c++編譯),就不再有錯誤了,得到結果:
after init,m=33
function of struct.
4. C語言實現類中方法——用函式指標在結構體中加入函式
first.h如下所示
/********* first.h *********/
#ifndef __FIRST__H_H
#define __FIRST__H_H
//way1:
struct test_st
{
int elem;
char* (*get_char)(char *str);
int (*get_int)(int in);
};
//way2: 先使用typedef宣告函式指標型別,再在struct中使用該函式指標型別的變數
typedef char* (*type_get_char)(char *str);
typedef int (*type_get_int)(int in);
typedef struct test_st
{
int elem;
type_get_char get_char;
type_get_int get_int;
}a_test_st;
#endif
first.c 如下所示
/********* first.c *********/
#include <stdio.h>
#include <string.h>
#include "first.h"
char *my_get_char(char *str);
int my_get_int(int in);
int main( void )
{
a_test_st *aTestSt;
char aStr[] = "abcdefg";
char *pStr = NULL;
int aInt = 0;
//申請記憶體空間
aTestSt = (a_test_st*)malloc(sizeof( a_test_st));
//為結構中變數賦值
memset(aTestSt, 0, sizeof(a_test_st));
aTestSt->elem = 45;
aTestSt->get_char = my_get_char;//為aTestSt中函式指標賦值
aTestSt->get_int = my_get_int;//為aTestSt中函式指標賦值
pStr = aTestSt->get_char( aStr);//呼叫aTestSt的函式
printf("aStr = %s/n",aStr);
aInt = aTestSt->get_int( aTestSt->elem);//呼叫aTestSt的函式
printf("aInt = %d/n", aInt);
free(aTestSt);//釋放aTestSt所指向記憶體空間
aTestSt = NULL;//置空
return 0;
}
char *my_get_char(char *str)
{//將str前兩個字元返回
char *pstr = NULL;
pstr = str;
*pstr = *str;
*(pstr + 1) = *(str + 1);
*(pstr + 2) = '/0';
return pstr;
}
int my_get_int(int in)
{
return in + 2;
}