码迷,mamicode.com
首页 > 编程语言 > 详细

C语言实现伪面向对象

时间:2018-09-19 19:58:16      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:头文件   str   实例   保护   cti   全局   new   something   fifo   

【1】每一个C文件都是一个伪类,除了main()函数所在的C文件。

【2】在C文件顶部定义该伪类的结构体,结构体内其实并没有必要使用函数指针来模拟成员函数。

struct fifo_t
{
    uint8_t        *buf;
    uint32_t    size;
    uint32_t    in;
    uint32_t    out;
};

【3】NEW。

通过类似的函数来创建新的伪类对象/实例。销毁类似。

struct fifo_t * fifo_create(uint32_t size)
{
    struct fifo_t * fifo = malloc(sizeof(struct fifo_t));
    /*
    
do something */ return fifo; }

【4】私有函数前加static关键字

static void * __fifo_a_private_func(struct fifo_t *fifo,int arg)

【5】头文件中只包含结构体声明和函数的声明,保护结构体内的【私有变量】不被直接读写。

struct fifo_t;
struct fifo_t * fifo_create(uint32_t size);
void fifo_destroy(struct fifo_t *fifo);
/*
    some other functions
*/

【6】没有继承。
  一般也不需要继承,实在需要就换C++好了。

【7】只有一个对象/实例的情况。其实这种情况才比较常见,可以放弃*_create()和*_destroy()函数,头文件中也只需要函数声明,这样更彻底地保护私有变量。整个C文件中只有一个有static前缀的结构体实例,函数中也很明显的区分出函数内部的局部变量和本文件的全局变量(对象)。

struct transmit_t
{
     int        fd;
    /*
    */
};
static struct transmit_t transmit =
{
    .fd = -1
};
int transmit_init()
{
    transmit.fd = // some thing
    /*
    */  
}
void transmit_destroy()
{
    /*
    */
}
/*
  some function
*

 

C语言实现伪面向对象

标签:头文件   str   实例   保护   cti   全局   new   something   fifo   

原文地址:https://www.cnblogs.com/hua946/p/9675920.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!