Tag: private

C中的“私有”结构成员与const

为了拥有一个干净的代码,使用一些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: […]