C 中的不透明(抽象)数据类型 [英] opaque (abstract) data types in C

查看:34
本文介绍了C 中的不透明(抽象)数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>
#ifndef API
#define API

struct trytag;
typedef struct trytag try;

void trial (try *);

#endif

文件 core.h

#ifndef CORE
#define CORE
struct trytag
{
    int a;
    int b;
};
#endif

文件func.c

#include "api.h"
#include "core.h"

void trial (try *tryvar)
{
    tryvar->a = 1;
    tryvar->b = 2;
}

文件 main.c

#include "api.h"

int main ()
{
    try s_tryvar;

    trial(&s_tryvar);

    printf("a = %d
b = %d
", s_tryvar.a, s_tryvar.b);
}

当我编译时,我得到:

main.c:5: error: storage size of ‘s_tryvar’ isn’t known

如果我在 main.c 中包含 core.h 这个错误不会出现,因为 try 是在 core.h 中定义的.但我希望结构 trymain.c 隐藏——它不应该知道 try 结构的成员.我错过了什么?

If I include core.h in main.c this error doesn't come as try is defined in core.h. But I want the structure try to be hidden to main.c — it should not know the members of try structure. What am I missing?

推荐答案

我认为您尝试做的事情是不可能的.编译器需要知道编译main.ctry 结构有多大.如果你真的希望它是不透明的,那么制作一个通用的指针类型,而不是直接在 main() 中声明变量,而是制作 alloc_try()free_try() 函数来处理创建和删除.

I don't think what you're trying to do is possible. The compiler needs to know how big a try structure is to compile main.c. If you really want it to be opaque, make a generic pointer type, and instead of declaring the variable directly in main(), make alloc_try() and free_try() functions to handle the creation and deletion.

像这样:

api.h:

#ifndef API
#define API

struct trytag;
typedef struct trytag try;

try *alloc_try(void);
void free_try(try *);
int try_a(try *);
int try_b(try *);
void trial (try *);

#endif

core.h:

#ifndef CORE
#define CORE
struct trytag
{
    int a;
    int b;
};
#endif

func.c:

#include "api.h"
#include "core.h"
#include <stdlib.h>

try *alloc_try(void)
{
    return malloc(sizeof(struct trytag));
}

void free_try(try *t)
{
    free(t);
}

int try_a(try *t)
{
    return t->a;
}

int try_b(try *t)
{
    return t->b;
}

void trial(try *t)
{
    t->a = 1;
    t->b = 2;
}

main.c:

#include <stdio.h>
#include "api.h"

int main()
{
    try *s_tryvar = alloc_try();

    trial(s_tryvar);
    printf("a = %d
b = %d
", try_a(s_tryvar), try_b(s_tryvar));

    free_try(s_tryvar);
}

这篇关于C 中的不透明(抽象)数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆