C语言与面向对象

问题一:C++的private关键字主要作用是封装,那么C语言如何完成同样的需求?

答:封装就是不给人看到,依着这个思路,我们来看看优秀的代码是怎么实现的.

apache里的内存池这一概念,它的声明在apr_pool.h里,

/** The fundamental pool type */
typedef struct apr_pool_t apr_pool_t;

而它的定义却在apr_pool.c里,

struct apr_pool_t {
    apr_pool_t           *parent;
    apr_pool_t           *child;
    apr_pool_t           *sibling;
    apr_pool_t          **ref;
    cleanup_t            *cleanups;
    cleanup_t            *free_cleanups;
    apr_allocator_t      *allocator;
    struct process_chain *subprocesses;
    apr_abortfunc_t       abort_fn;
    apr_hash_t           *user_data;
    const char           *tag;

#if !APR_POOL_DEBUG
    apr_memnode_t        *active;
    apr_memnode_t        *self; /* The node containing the pool itself */
    char                 *self_first_avail;

#else /* APR_POOL_DEBUG */
    apr_pool_t           *joined; /* the caller has guaranteed that this pool
                                   * will survive as long as ->joined */
    debug_node_t         *nodes;
    const char           *file_line;
    apr_uint32_t          creation_flags;
    unsigned int          stat_alloc;
    unsigned int          stat_total_alloc;
    unsigned int          stat_clear;
#if APR_HAS_THREADS
    apr_os_thread_t       owner;
    apr_thread_mutex_t   *mutex;
#endif /* APR_HAS_THREADS */
#endif /* APR_POOL_DEBUG */
#ifdef NETWARE
    apr_os_proc_t         owner_proc;
#endif /* defined(NETWARE) */
    cleanup_t            *pre_cleanups;
    cleanup_t            *free_pre_cleanups;
};

 

这样做的好处是外界(也即指apr_pool.c以外的文件)无法直接访问内存池的成员.内存池只提供类似这样的接口:

apr_pool_create(&ptemp, pconf);
apr_pool_tag(ptemp, "ptemp");

apr_pool_clear(plog);

apr_pool_destroy(ptemp);
apr_pool_lock(pconf, 1);

这样的是不是很像C++里的public和private的运用.

 

同样道理,在apr_pool_t里有一个成员cleanups,我们可以看到它的定义和声明都在apr_pool.c里,

typedef struct cleanup_t cleanup_t;

struct cleanup_t {
    struct cleanup_t *next;
    const void *data;
    apr_status_t (*plain_cleanup_fn)(void *data);
    apr_status_t (*child_cleanup_fn)(void *data);
};

这样做,一般的apache开发者根本都不知道有struct cleanup_t这种东西.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值