我尝试使用虚函数表在C中使用虚函数实现集合,并且由于错误而导致初始化虚函数表时出现问题:
error: designator in initializer for scalar type 'set *' (aka 'struct _set *')
我被赋予了(它的任务)一个通用的' set.c'和' set.h'文件作为一个接口,所以我怀疑我可能没有接近正确实现它的想法。
以下是集合标题的相关部分:
typedef struct _set{
const struct _set_vtable *vtable;
const item_vtable *i_vtable;
int size;
} set;
typedef bool (*SET_ADD_FXN)(set *, const void *);
typedef bool (*SET_CONTAINS_FXN)(const set *, const void *);
typedef void (*SET_PRINT_FXN)(const set *);
typedef void (*SET_DESTROY_FXN)(set *);
typedef struct _set_vtable
{
SET_ADD_FXN add;
SET_CONTAINS_FXN contains;
SET_PRINT_FXN print;
SET_DESTROY_FXN destroy;
} set_vtable;
bool set_add(set *s, const void *item);
bool set_contains(const set *s, const void *item);
void set_print(const set *s);
void set_destroy(set *s);
int set_size(const set *s);
set.c文件只是通过set函数表将函数调用转发给指向的函数:
bool set_add(set *s, const void *item)
{
return s->vtable->add(s, item);
}
...
所以,这是我尝试实施' set231'这是一个具有特定功能的集合:
//set231.h
#include "set.h"
typedef struct{
set * const interface;
const char **items;
} set231;
set231 *set231_create();
int set231_size(set231 *);
bool set231_add(set231 *, const void *);
bool set231_contains(const set231 *, const void *);
void set231_print(const set231 *);
void set231_destroy(set231 *);
extern set_vtable set231_vtable;
extern item_vtable set231_ivtable;
//set231.c
#include "set231.h"
const int INITIAL_CAPACITY = 4;
const int STRING_LENGTH = 16;
set231 *set231_create(){
set231 *new = {
.interface = &((set *){
.vtable = &set231_vtable,
.i_vtable = &((item_vtable *){
.compare = strcmpv,
.destroy = free,
.print = str_print,
.clone = strdupe
}),
.size = 0
}),
.items = (void *) malloc(sizeof(char *) * INITIAL_CAPACITY)
};
return new;
}
int set231_size(set231 *s){...}
bool set231_add(set231 *s, const void *item){...}
bool set231_contains(const set231 *s, const void *item){...}
void set231_print(const set231 *s){...}
void set231_destroy(set231 *s){...}
set_vtable set231_vtable =
{
.add = set231_add,
.contains = set231_contains,
.print = set231_print,
.destroy = set231_destroy
};
item_vtable set231_ivtable =
{
.compare = strcmpv,
.destroy = free,
.print = str_print,
.clone = strdupe
};
编译时,我得到初始化器错误的指示符,以及给出设置接口的虚拟表函数的警告,这些函数专门询问set231而不是set。
warning: incompatible pointer types initializing 'SET_ADD_FXN' (aka 'bool (*)(set *, const void *)') with an expression of type 'bool (set231 *, const void *)'