为什么我不能创建不透明的数据类型? [英] Why can't I create an opaque data type?

查看:30
本文介绍了为什么我不能创建不透明的数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用不透明数据类型来了解它们.主要问题是我不断收到不完整"错误.

I'm trying to experiment with opaque data types to get an understanding of them. The main problem is that I keep getting an 'incomplete' error.

ma​​in.c

#include <stdio.h>
#include <stdlib.h>
#include "blepz.h"

int main()
{
    setfnarp(GOO,5);
    int loogaboo = getfnarp(GOO);

    printf("%i", loogaboo);
    return 0;
}

fnarpishnoop.c

#include "blepz.h"

struct noobza {
    int fnarp;
};

void setfnarp(struct noobza x, int i){
    x.fnarp = i;
};

int getfnarp(struct noobza x){
    return x.fnarp;
};

blepz.h

struct noobza;

void setfnarp(struct noobza x, int i);

int getfnarp(struct noobza x);

struct noobza GOO;

我显然不明白这里的一些东西,我希望有人能帮助我弄清楚不透明数据类型是如何实现的,如果它们的重点是你很难找到它们的实际代码.

I clearly don't understand something here and I was hoping someone could help me figure out how opaque data types are implemented if the whole point of them is that you have a hard time finding actual code for them.

推荐答案

使用未声明内容的 struct 会产生类型不完整"错误,正如您已经提到的.

Using a struct that you haven't declared the contents of gives an "incomplete type" error, as you have already mentioned.

相反,使用指向 struct 的指针和返回指向 struct 的指针的函数,如下所示:

Instead, use a pointer to the struct and a function that returns a pointer to the struct, like this:

struct noobza;

struct noobza *create_noobza(void);

void setfnarp(struct noobza *x, int i);

int getfnarp(struct noobza *x);

struct noobza *GOO;

...

#include <stdlib.h>
#include "blepz.h"

struct noobza {
    int fnarp;
};

struct noobza *create_noobza(void)
{
    return calloc(1, sizeof(struct noobza));
}

void setfnarp(struct noobza *x, int i){
    x->fnarp = i;
};

int getfnarp(struct noobza *x){
    return x->fnarp;
};

...

#include <stdio.h>
#include <stdlib.h>
#include "blepz.h"

int main()
{
    GOO = create_noobza();
    setfnarp(GOO,5);
    int loogaboo = getfnarp(GOO);

    printf("%i", loogaboo);
    return 0;
}

这篇关于为什么我不能创建不透明的数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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