/* Rectangle.h */
typedef struct tagPoint
{
long x;
long y;
}Point;
typedef struct tagRectangle
{
Point LeftTop;
long width;
long height;
}Rectangle;
typedef int RectClassID;
int Rectangle_New(RectClassID id);
int Rectangle_SetLeftTopPoint(RectClassID id, Point p);
Point* Rectangle_GetLeftTopPoint(RectClassID id, Point* out_point);
/* Rectangle.c */
#include "Rectangle.h"
typedef struct tagRectangleItem
{
Rectangle rect;
RectClassID id;
}RectangleItem;
#define MAX_ITEM 100
RectangleItem g_tRectIem[MAX_ITEM];/* 用链表记录更好,不限个数 */
int g_Count = 0;
static Rectangle* Rectangle_FindItem(RectClassID id)
{
int i = 0;
for (i = 0; i < g_Count; ++i)
{
if (g_tRectIem[i].RectClassID == id)
{
return &g_tRectIem[i].rect;
}
}
return NULL;
}
int Rectangle_GetClassID()
{
if (g_Count < MAX_ITEM)
{
return g_Count++;
}
else
{
return -1;
}
}
int Rectangle_New(RectClassID id)
{
if (g_Count < MAX_ITEM && g_Count > 0)
{
g_tRectIem[g_Count++].pRect = id;
memset(&g_tRectIem[g_Count - 1].rect, 0, sizeof(Rectangle));
return 0; //success
}
else
{
return -1; //failed
}
}
int Rectangle_SetLeftTopPoint(RectClassID id, Point p)
{
Rectangle* pRect = Rectangle_FindItem(id);
if (NULL != pRect)
{
pRect->LeftTop = p;
return 0;
}
else
{
return -1;
}
}
Point* Rectangle_GetLeftTopPoint(RectClassID id, Point* out_point)
{
Rectangle* pRect = Rectangle_FindItem(id);
if (NULL != pRect)
{
memcpy(out_point, &pRect->LeftTop, sizeof(Point));
}
else
{
return NULL;//failed
}
}
/* main.c */
void main()
{
Point p={3,4};
int class_id = Rectangle_GetClassID();
Rectangle_New(class_id);
/* 实现只能如下方式调用 */
Rectangle_SetLeftTopPoint(class_id, p);
}