如何使结构成员的私人? [英] How to make struct members private?

查看:113
本文介绍了如何使结构成员的私人?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义在头文件中的结构如下所示:

I define a structure in a header file like so:

typedef struct {
    void *data;
} point;

我想防止他人直接访问*数​​据,所以我想我会在声明.c文件的结构,而不是和使用类似的extern typedef结构点; 在头文件。这并不然而工作。

I want to keep other people from accessing *data directly, so I thought I'd declare the structure in the .c file instead and use something like extern typedef struct point; in the header file. That doesn't work however.

什么是实现这一目标的最佳途径?

What's the best way to achieve this?

推荐答案

在你的(公)头文件:

typedef struct point point;

在你的 .C 文件:

struct point
{
    void *data;
};

请注意,您的code的用户将不再能够创建一个在堆栈上,因为编译器不知道它有多大。您可能需要提供哪些分配内存,并将其地址返回给调用者一个 point_create()功能。

Note that users of your code will no longer be able to create a point on the stack, as the compiler doesn't know how big it is. You may have to provide a point_create() function which allocates memory and returns its address to the caller.

这篇关于如何使结构成员的私人?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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