C语言与面向对象

来源:互联网 发布:js代码dos 编辑:程序博客网 时间:2024/05/01 19:08

问题一: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这种东西.