问题一: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这种东西.
分享到:
相关推荐
用C语言实现面向对象编程.pdf
附件是在VS2012下用C语言实现面向对象的示例代码,并实现设计模式中的工厂模式
【C语言】C语言实现面向对象编程之封装代码.,完整的代码,可以在Linux和VS环境运行。【C语言】C语言实现面向对象编程之封装代码.rar
众所周知,C 语言是面向过程的编程语言,把它和“面向对象”连接起来似乎不太可能。其实“面向对象”是一种思想,编程语言是实现思想的工具。文章通过 C 语言中的结构体实现了“面向对象”的继承、封装和多态,阐述了...
没错是C语言的面向对象,对于用C写出可扩展性强的代码和设计模式应用非常有帮助, 非常有助于嵌入式系统的开发.
C语言面向对象(针对较大型软件
此实例文件是文章《学会C语言面向对象编程,弄清面向对象实质。》的附件https://blog.csdn.net/weixin_42523774/article/details/105649779,是为了告诉大家如何用C语言实现面向对象的语言。
c语言实现面向对象OOP
C语言面向对象编程与设计模式
用c语言实现面向对象用c语言实现面向对象
C语言面向对象程序设计(ppt) C语言面向对象程序设计(ppt) C语言面向对象程序设计(ppt)
C语言下实现面向对象的三大特性:封装、继承、多态。注意:此文件是vs2010下的工程文件
c语言是面向过程的程序语言,可是用它也能实现面向对象,该代码给出实现面向对象的c源码
嵌入式编程时的面向对象
Object-C语言,用C语言实现面向对象
这是一个用C语言编写面向对象程序的软件开发平台,内附有标准版、简化版、编程实例及说明文档。提供全部源码! 对希望用面向对象的思想设计系统、用C语言实现编码的嵌入式软件工作者,提供了一个极好的解决方案。
C语言面向对象编程C语言面向对象编程
OOPC是指OOP(Object-Oriented Programming)与C语言的结合,它是一个面向对象C语言编程框架。它是一套C语言的宏,定义了OOP概念的关键字,借助于这一套宏,实现面向对象的特性,如类、对象、继承、接口、多态、消息等...
C语言面向对象编程技术,是C语言开发者不可多得的技术书籍
用c++写的,没有文件操作的,利用面向对象思想的小通讯录。