typedef struct LIBIO {
io_info_t *info;
int (*ropen)(char *devname, int *sample, short *channel, short *bit) {
printf("1\n"); // 錯誤:結構體中不能定義函數體
}
} io_t;
C 語言結構體只能聲明函數指針類型,不能在結構體內部實現函數體。函數指針本質是變量,需單獨賦值。
// 1. 聲明函數指針類型
typedef int (*RopenFunc)(char *devname, int *sample, short *channel, short *bit);
// 2. 結構體中聲明指針成員
typedef struct LIBIO {
io_info_t *info;
RopenFunc ropen; // 僅聲明指針
} io_t;
// 3. 實現具體函數
int my_ropen(char *devname, int *sample, short *channel, short *bit) {
printf("1\n");
return 0;
}
// 4. 賦值給結構體實例
io_t my_io;
my_io.ropen = my_ropen; // 賦值函數地址
// 5. 調用
my_io.ropen("dev", &sample, &channel, &bit);
C++ 允許結構體/類內定義成員函數(方法),但 C 必須用函數指針模擬多態。