如何隐藏在C结构的声明? [英] How can I hide the declaration of a struct in C?

查看:130
本文介绍了如何隐藏在C结构的声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个问题为什么我们要的typedef一个struct ?所以经常用C ,放松回答说:

In the question Why should we typedef a struct so often in C?, unwind answered that:

在后一种情况下,你不能返回
  点按值,因为它的
  声明是从用户隐藏
  头文件。这是一种技术
  在GTK +应用广泛,比如

In this latter case, you cannot return the Point by value, since its declaration is hidden from users of the header file. This is a technique used widely in GTK+, for instance.

如何申报隐藏做到的呢?为什么我不能用价值归路?

How is declaration hiding accomplished? Why can't I return the Point by value?

地址:

我明白了为什么我不能返回值的结构,但是,目前还很难看出为什么我不能在尊重我的功能这一点。即如果我的结构有一个名为Ÿ成员,为什么我不能呢?

I understood why I can't return the struct by value, but, is still hard to see why i can't deference this point in my function. i.e. If my struct have member named y, why i can't do it?

 pointer_to_struct->y = some_value; 

我为什么要使用的方法来做到这一点? (像GTK +)

Why should I use methods to do it? (Like Gtk+)

谢谢你们,和遗憾,我的英文不好试。

Thanks guys, and sorry for my bad english again.

推荐答案

有一个在图书馆的这个例子中,使用公共头文件,私人头文件和实施文件。

Have a look at this example of a library, using a public header file, a private header file and an implementation file.

在文件中的 public.h 的:

struct Point;

Point* getSomePoint();

在文件中的 private.h 的:

struct Point
{
    int x;
    int y;
}

在文件中的 private.c 的:

Point* getSomePoint()
{
    /* ... */
}

如果您combile这三个文件到库中,你只给的 public.h 的和库目标文件库的消费者。

If you combile these three files into a library, you only give public.h and the library object file to the consumer of the library.

getSomePoint 必须返回一个指向,因为 public.h 的呢没有定义的大小,这是唯一一个结构,它的存在。图书馆的消费者可以使用指针的,但不能左右访问成员或复制,因为他们不知道该结构的大小。

getSomePoint has to return a pointer to Point, because public.h does not define the size of Point, only that is a struct and that it exists. Consumers of the library can use pointers to Point, but can not access the members or copy it around, because they do not know the size of the structure.

关于你提到的另一个问题:
你不能因为取消引用使用该库的程序不只有从的 private.h 的,不包含成员声明中的信息。因此,它不能访问点结构的成员。

Regarding your further question: You can not dereference because the program using the library does only have the information from private.h, that does not contain the member declarations. It therefore can not access the members of the point structure.

您可以看到这是C的封装特性,就像你一个C ++类的数据成员声明为private。

You can see this as the encapsulation feature of C, just like you would declare the data members of a C++ class as private.

这篇关于如何隐藏在C结构的声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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