我正在阅读用C语言实现接口,我真的想试一试。我以为我知道怎么做但是我被困在最后一块拼图上。我不能在不破坏封装的情况下继续。我有两个"对象"," Fruit"和#34; Apple"。我希望用户处理Fruit对象,但永远不知道底层类型(在这种情况下为Apple)。
我似乎无法做到,因为我无法找到Apple
知道如何使用Fruit
创建自己的方法。我不想让Main.c
看到constructor
,但Apple.c
需要看到它。我不知道如何继续。
我有以下项目结构:
Fruit.h
// fruit is too general to be created here
// fruit objects can only be created in other files
typedef struct Fruit Fruit;
void grow(Fruit *f);
Fruit.c
#include "Fruit.h"
// It's very important user cannot see 'struct Fruit'
struct Fruit
{
void *fruit_obj; // Fruit object of unknown type
void(*grow)(void*); // grow function for that type of fruit
};
// User should not see this!
// Fruit objects can only be made from other files!
Fruit* constructor(void *fruit_obj, void(*grow)(void*))
{
Fruit *f = malloc(sizeof(Fruit));
f->fruit_obj = fruit_obj;
f->grow = grow;
return f;
}
void grow(Fruit *f)
{
f->grow(f->fruit_obj);
}
Apple.h
#include "Fruit.h"
Fruit* createApple();
Apple.c
#include "Apple.h"
// The user should never ever see this struct.
struct Apple
{
int size;
}
void apple_grow(void *a)
{
struct Apple *apple = (struct Apple*)a;
apple->size++;
printf("Your apple has grown to %d size!\n", apple->size);
}
// My attempt to make me able to create fruit from this file.
extern Fruit* constructor(void *fruit_obj, void(*grow)(void*));
Fruit* createApple()
{
struct Apple *a = malloc(sizeof(struct Apple));
a->size = 1;
Fruit *f = constructor(a, &apple_grow);
// LINKER ERROR: 'undefined reference to 'constructor''
return f;
}
MAIN.C
#include "Apple.h"
int main()
{
Fruit *f = createApple();
grow(f);
}