用标准C(ansi c) 实现 C++(面向对象)的私有成员保护

 

/* 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);

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值