为了获得干净的代码,使用一些 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,编译器不会抱怨任何事情,即使有一些严格的标志,但我怎么能确定这真的没问题?