gpt4 book ai didi

c - 在 C 中部分转发声明结构的成语?

转载 作者:太空宇宙 更新时间:2023-11-04 01:02:20 25 4
gpt4 key购买 nike

在 C++ 中,当我们定义类或结构时,我们将一些字段设为私有(private),一些设为公有:

struct foo {
public:
int x;
private:
float y;
}

.在 C 中我们不能这样做,但我们可以使用前向声明和 setter/getter 。在 foo.h 中:

struct foo;

foo_get_x(struct foo* f);

foo.c 中:

struct foo {
int x;
float y;
}

foo_get_x(struct foo* f) { return f->x; }

现在,假设出于某些原因(例如性能),我希望能够从仅看到 foo.h 的代码直接访问 x,而无需函数调用。我想要一些方法来以某种方式定义 x ,并且对我隐藏 struct foo 的其余部分。我在想也许我可以对 union 采取一些技巧;或者可能与

struct foo {
int x;
char* more_data[];
}

一种结构,我在这里和那里都注意到了。你有什么建议?

最佳答案

你可以这样做

/* public header */
struct foo
{
/* "public" parts */
};

/* elsewhere */
struct bar
{
struct foo fooPart;
/* other stuff */
};

您可以自由地将指向 struct bar 的指针转换为 struct foo* 类型并返回到 struct bar*,这是保证定义明确。

因此,您可以编写分配 bar 并返回 foo* 的函数,以及接受 foo* 但使用

这就是早期的 OO 软件是如何用 C 编写的。

关于c - 在 C 中部分转发声明结构的成语?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33634405/

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