繁体   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