相关疑难解决方法(0)

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: 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" …
Run Code Online (Sandbox Code Playgroud)

c struct const private

9
推荐指数
2
解决办法
1759
查看次数

标签 统计

c ×1

const ×1

private ×1

struct ×1