簡體   English   中英

如何使用vTable或C中的函數指針數組創建結構?

[英]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;

注意事項:

  1. 我固定了標簽標識符,所以它不會遵循C標准
  2. 我將函數指針 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM