为了控制结构成员并强制程序员使用 getter/setter 函数,我想编写如下模式的代码:
/* Header file: point.h */
...
/* define a struct without full struct definition. */
struct point;
/* getter/setter functions. */
int point_get_x(const struct point* pt);
void point_set_x(struct point* pt, int x);
...
//--------------------------------------------
/* Source file: point.c */
struct point
{
int x, y;
};
int point_get_x(const struct point* pt) {return pt->x; }
void point_set_x(struct point* pt, int x) {pt->x = x;}
//--------------------------------------------
/* Any source file: eg. main.c */
#include "point.h"
int main()
{
struct point pt;
// Good: cannot access struct members directly.
// He/She should use getter/setter functions.
//pt.x = 0;
point_set_x(&pt, 0);
}
但是这段代码不能用 MSVC++ 2010 编译。
我应该为编译做哪些更改?
注意:我使用 ANSI-C (C89) 标准,而不是 C99 或 C++。