[英]How can I create a struct with a vTable or array of function pointers in C?
我在用C聲明帶有函數指針數組(vTable)的結構時遇到問題,因為如果我先聲明函數指針, 並且參數需要是指向自身的自引用“ this”指針 ,則該結構沒有尚未宣布。 如果在結構之后聲明函數指針,則函數類型尚未聲明,因此編譯器在設置結構時會抱怨:
#include <stdio.h>
#include <stdlib.h>
typedef int (*math_operation) (struct _MyClass *this,int a, int b);
typedef struct _MyClass{
int number;
char name[50];
math_operation *vTable[50];
} MyClass;
int main(void)
{
MyClass *test;
return(EXIT_SUCCESS);
}
創建具有指向父結構的“ this”指針的函數指針數組的正確方法是什么?
您只需要在全局名稱空間中對結構進行前向聲明:
struct MyClass_;
typedef int math_operation(struct MyClass_ *this, int a, int b);
typedef struct MyClass_{
int number;
char name[50];
math_operation *vTable[50];
} MyClass;
注意事項:
我將函數指針 typedef更改為函數類型 typedef。 您已經將vTable
定義為指向math_operation
的指針數組。 一個指針聲明符是多余的。 這還有一個不錯的實用工具,它允許您按預期用途聲明函數,並讓編譯器類型對其進行檢查:
math_operation add; // .. Later int add(struct MyClass_ *this, int a, int b) { return a + b; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.