gpt4 book ai didi

c - 如何在 C 中隐藏结构的声明?

转载 作者:太空狗 更新时间:2023-10-29 16:45:32 27 4
gpt4 key购买 nike

在问题Why should we typedef a struct so often in C? , unwind 回答说:

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.

声明隐藏是如何实现的?为什么我不能按值返回点数?

添加:

我明白为什么我不能按值返回结构,但是,仍然很难理解为什么我不能在我的函数中引用这一点。即如果我的结构有名为 y 的成员,为什么我不能这样做?

 pointer_to_struct->y = some_value; 

为什么要用方法来做? (像 Gtk+)

谢谢你们,再次抱歉我的英语不好。

最佳答案

看看这个库示例,使用公共(public)头文件、私有(private)头文件和实现文件。

在文件 public.h 中:

struct Point;

struct Point* getSomePoint();

在文件 private.h 中:

struct Point
{
int x;
int y;
}

在文件 private.c 中:

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

如果你把这三个文件编译成一个库,你只是把public.h和库对象文件给了库的消费者。

getSomePoint 必须返回指向 Point 的指针,因为 public.h 没有定义 Point 的大小>,只有它是一个结构并且它存在。库的使用者可以使用指向 Point 的指针,但不能访问成员或复制它,因为他们不知道结构的大小。

关于您的进一步问题:您不能取消引用,因为使用该库的程序只有来自 private.h 的信息,不包含成员声明。因此它不能访问点结构的成员。

您可以将此视为 C 的封装特性,就像您将 C++ 类的数据成员声明为私有(private)一样。

关于c - 如何在 C 中隐藏结构的声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1154709/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com