【发布时间】:2012-12-12 04:23:06
【问题描述】:
为了有一个干净的代码,使用一些 OO 概念可能很有用,即使在 C 中也是如此。 我经常编写由一对 .h 和 .c 文件组成的模块。问题是模块的用户必须小心,因为私有成员在 C 中不存在。使用 pimpl 习惯用法或抽象数据类型是可以的,但它添加了一些代码和/或文件,并且需要更重的代码。我讨厌在不需要访问器时使用访问器。
这里有一个想法,它提供了一种让编译器抱怨对“私人”成员的无效访问的方法,只需要一些额外的代码。这个想法是定义两次相同的结构,但为模块的用户添加了一些额外的“const”。
当然,使用演员表仍然可以写入“私人”成员。但重点只是避免模块用户出错,而不是安全地保护内存。
/*** 2DPoint.h module interface ***/
#ifndef H_2D_POINT
#define H_2D_POINT
/* 2D_POINT_IMPL need to be defined in implementation files before #include */
#ifdef 2D_POINT_IMPL
#define _cst_
#else
#define _cst_ const
#endif
typedef struct 2DPoint
{
/* public members: read and write for user */
int x;
/* private members: read only for user */
_cst_ int y;
} 2DPoint;
2DPoint *new_2dPoint(void);
void delete_2dPoint(2DPoint **pt);
void set_y(2DPoint *pt, int newVal);
/*** 2dPoint.c module implementation ***/
#define 2D_POINT_IMPL
#include "2dPoint.h"
#include <stdlib.h>
#include <string.h>
2DPoint *new_2dPoint(void)
{
2DPoint *pt = malloc(sizeof(2DPoint));
pt->x = 42;
pt->y = 666;
return pt;
}
void delete_2dPoint(2DPoint **pt)
{
free(*pt);
*pt = NULL;
}
void set_y(2DPoint *pt, int newVal)
{
pt->y = newVal;
}
#endif /* H_2D_POINT */
/*** main.c user's file ***/
#include "2dPoint.h"
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
2DPoint *pt = new_2dPoint();
pt->x = 10; /* ok */
pt->y = 20; /* Invalid access, y is "private" */
set_y(pt, 30); /* accessor needed */
printf("pt.x = %d, pt.y = %d\n", pt->x, pt->y); /* no accessor needed for reading "private" members */
delete_2dPoint(&pt);
return EXIT_SUCCESS;
}
现在,问题来了:这个技巧是否符合 C 标准? 它在 GCC 上运行良好,编译器不会抱怨任何事情,即使有一些严格的标志,但我怎么能确定这真的没问题?
【问题讨论】:
-
有趣的方法。我不知道这是否是明确定义的行为。我建议不要这样做,因为它与惯用的 C 相去甚远……要么使用不透明的结构(在
.c文件中定义)并提供访问器,要么记录不分配字段的文档。 -
我认为 Thomas 的答案应该是一个“真实”的答案——也许有几个例子。
-
顺便问一下,
2DPoint是如何形成有效标识符的? -
如果您想更好地了解不透明结构的工作原理,我在 H2CO3 的回答下详细阐述了 Thomas 的回答(无意中,没有看到评论)。
标签: c struct constants private