不知道有多少人去了解过语言的发展史,早期c语言的语法功能其实比较简单。随着应用需求和场景的变化,c语言的语法功能在不断升级变化。
虽然我们的教材有这么一个结论:c语言是面向过程的语言,c++是面向对象的编程语言,但面向对象的概念是在c语言阶段就有了,而且应用到了很多地方,比如某些操作系统内核、通信协议等。
面向对象编程,也就是大家说的oop(object oriented programming)并不是一种特定的语言或者工具,它只是一种设计方法、设计思想,它表现出来的三个最基本的特性就是封装、继承与多态。
为什么要用c语言实现面向对象
阅读文本之前肯定有读者会问这样的问题:我们有c++面向对象的语言,为什么还要用c语言实现面向对象呢?
c语言这种非面向对象的语言,同样也可以使用面向对象的思路来编写程序的。只是用面向对象的c++语言来实现面向对象编程会更简单一些,但是c语言的高效性是其他面向对象编程语言无法比拟的。
当然使用c语言来实现面向对象的开发相对不容易理解,这就是为什么大多数人学过c语言却看不懂linux内核源码。
所以这个问题其实很好理解,只要有一定c语言编程经验的读者都应该能明白:面向过程的c语言和面向对象的c++语言相比,代码运行效率、代码量都有很大差异。在性能不是很好、资源不是很多的mcu中使用c语言面向对象编程就显得尤为重要。
具备条件
要想使用c语言实现面向对象,首先需要具备一些基础知识。比如:(c语言中的)结构体、函数、指针,以及函数指针等,(c++中的)基类、派生、多态、继承等。
首先,不仅仅是了解这些基础知识,而是有一定的编程经验,因为上面说了“面向对象是一种设计方法、设计思想”,如果只是停留在字面意思的理解,没有这种设计思想肯定不行。
因此,不建议初学者使用c语言实现面向对象,特别是在真正项目中。建议把基本功练好,再使用。
利用c语言实现面向对象的方法很多,下面就来描述最基本的封装、继承和多态。
封装
封装就是把数据和函数打包到一个类里面,其实大部分c语言编程者都已近接触过了。
c 标准库中的 fopen(), fclose(), fread(), fwrite()等函数的操作对象就是 file。数据内容就是 file,数据的读写操作就是 fread()、fwrite(),fopen() 类比于构造函数,fclose() 就是析构函数。
这个看起来似乎很好理解,那下面我们实现一下基本的封装特性。
#ifndef shape_h#define shape_h#include // shape 的属性typedef struct { int16_t x; int16_t y; } shape;// shape 的操作函数,接口函数void shape_ctor(shape * const me, int16_t x, int16_t y);void shape_moveby(shape * const me, int16_t dx, int16_t dy);int16_t shape_getx(shape const * const me);int16_t shape_gety(shape const * const me);#endif /* shape_h */
这是 shape 类的声明,非常简单,很好理解。一般会把声明放到头文件里面 “shape.h”。来看下 shape 类相关的定义,当然是在 “shape.c” 里面。
#include shape.h// 构造函数void shape_ctor(shape * const me, int16_t x, int16_t y){ me->x = x; me->y = y;}void shape_moveby(shape * const me, int16_t dx, int16_t dy) { me->x += dx; me->y += dy;}// 获取属性值函数int16_t shape_getx(shape const * const me) { return me->x;}int16_t shape_gety(shape const * const me) { return me->y;} 再看下 main.c#include shape.h /* shape class interface */#include /* for printf() */int main() { shape s1, s2; /* multiple instances of shape */ shape_ctor(&s1, 0, 1); shape_ctor(&s2, -1, 2); printf(shape s1(x=%d,y=%d), shape_getx(&s1), shape_gety(&s1)); printf(shape s2(x=%d,y=%d), shape_getx(&s2), shape_gety(&s2)); shape_moveby(&s1, 2, -4); shape_moveby(&s2, 1, -2); printf(shape s1(x=%d,y=%d), shape_getx(&s1), shape_gety(&s1)); printf(shape s2(x=%d,y=%d), shape_getx(&s2), shape_gety(&s2)); return 0;} 编译之后,看看执行结果:shape s1(x=0,y=1)shape s2(x=-1,y=2)shape s1(x=2,y=-3)shape s2(x=0,y=0)
整个例子,非常简单,非常好理解。以后写代码时候,要多去想想标准库的文件io操作,这样也有意识的去培养面向对象编程的思维。
继承
继承就是基于现有的一个类去定义一个新类,这样有助于重用代码,更好的组织代码。在 c 语言里面,去实现单继承也非常简单,只要把基类放到继承类的第一个数据成员的位置就行了。
例如,我们现在要创建一个 rectangle 类,我们只要继承 shape 类已经存在的属性和操作,再添加不同于 shape 的属性和操作到 rectangle 中。
下面是 rectangle 的声明与定义:
#ifndef rect_h#define rect_h#include shape.h // 基类接口// 矩形的属性typedef struct { shape super; // 继承 shape // 自己的属性 uint16_t width; uint16_t height;} rectangle;// 构造函数void rectangle_ctor(rectangle * const me, int16_t x, int16_t y, uint16_t width, uint16_t height);#endif /* rect_h */
#include rect.h// 构造函数void rectangle_ctor(rectangle * const me, int16_t x, int16_t y, uint16_t width, uint16_t height){ /* first call superclass’ ctor */ shape_ctor(&me->super, x, y); /* next, you initialize the attributes added by this subclass... */ me->width = width; me->height = height;}
我们来看一下 rectangle 的继承关系和内存布局:
因为有这样的内存布局,所以你可以很安全的传一个指向 rectangle 对象的指针到一个期望传入 shape 对象的指针的函数中,就是一个函数的参数是 “shape *”,你可以传入 “rectangle *”,并且这是非常安全的。这样的话,基类的所有属性和方法都可以被继承类继承!
#include rect.h #include int main() { rectangle r1, r2; // 实例化对象 rectangle_ctor(&r1, 0, 2, 10, 15); rectangle_ctor(&r2, -1, 3, 5, 8); printf(rect r1(x=%d,y=%d,width=%d,height=%d), shape_getx(&r1.super), shape_gety(&r1.super), r1.width, r1.height); printf(rect r2(x=%d,y=%d,width=%d,height=%d), shape_getx(&r2.super), shape_gety(&r2.super), r2.width, r2.height); // 注意,这里有两种方式,一是强转类型,二是直接使用成员地址 shape_moveby((shape *)&r1, -2, 3); shape_moveby(&r2.super, 2, -1); printf(rect r1(x=%d,y=%d,width=%d,height=%d), shape_getx(&r1.super), shape_gety(&r1.super), r1.width, r1.height); printf(rect r2(x=%d,y=%d,width=%d,height=%d), shape_getx(&r2.super), shape_gety(&r2.super), r2.width, r2.height); return 0;}
输出结果:
rect r1(x=0,y=2,width=10,height=15)rect r2(x=-1,y=3,width=5,height=8)rect r1(x=-2,y=5,width=10,height=15)rect r2(x=1,y=2,width=5,height=8)
多态
c++ 语言实现多态就是使用虚函数。在 c 语言里面,也可以实现多态。 现在,我们又要增加一个圆形,并且在 shape 要扩展功能,我们要增加 area() 和 draw() 函数。但是 shape 相当于抽象类,不知道怎么去计算自己的面积,更不知道怎么去画出来自己。而且,矩形和圆形的面积计算方式和几何图像也是不一样的。 下面让我们重新声明一下 shape 类:
#ifndef shape_h#define shape_h#include struct shapevtbl;// shape 的属性typedef struct { struct shapevtbl const *vptr; int16_t x; int16_t y; } shape;// shape 的虚表struct shapevtbl { uint32_t (*area)(shape const * const me); void (*draw)(shape const * const me);};// shape 的操作函数,接口函数void shape_ctor(shape * const me, int16_t x, int16_t y);void shape_moveby(shape * const me, int16_t dx, int16_t dy);int16_t shape_getx(shape const * const me);int16_t shape_gety(shape const * const me);static inline uint32_t shape_area(shape const * const me) { return (*me->vptr->area)(me);}static inline void shape_draw(shape const * const me){ (*me->vptr->draw)(me);}shape const *largestshape(shape const *shapes[], uint32_t nshapes);void drawallshapes(shape const *shapes[], uint32_t nshapes);#endif /* shape_h */
看下加上虚函数之后的类关系图:
5.1 虚表和虚指针
虚表(virtual table)是这个类所有虚函数的函数指针的集合。 虚指针(virtual pointer)是一个指向虚表的指针。这个虚指针必须存在于每个对象实例中,会被所有子类继承。 在《inside the c++ object model》的第一章内容中,有这些介绍。
5.2 在构造函数中设置vptr
在每一个对象实例中,vptr 必须被初始化指向其 vtbl。最好的初始化位置就是在类的构造函数中。事实上,在构造函数中,c++ 编译器隐式的创建了一个初始化的vptr。在 c 语言里面, 我们必须显示的初始化vptr。 下面就展示一下,在 shape 的构造函数里面,如何去初始化这个 vptr。
#include shape.h#include // shape 的虚函数static uint32_t shape_area_(shape const * const me);static void shape_draw_(shape const * const me);// 构造函数void shape_ctor(shape * const me, int16_t x, int16_t y) { // shape 类的虚表 static struct shapevtbl const vtbl = { &shape_area_, &shape_draw_ }; me->vptr = &vtbl; me->x = x; me->y = y;}void shape_moveby(shape * const me, int16_t dx, int16_t dy){ me->x += dx; me->y += dy;}int16_t shape_getx(shape const * const me) { return me->x;}int16_t shape_gety(shape const * const me) { return me->y;}// shape 类的虚函数实现static uint32_t shape_area_(shape const * const me) { assert(0); // 类似纯虚函数 return 0u; // 避免警告}static void shape_draw_(shape const * const me) { assert(0); // 纯虚函数不能被调用}shape const *largestshape(shape const *shapes[], uint32_t nshapes) { shape const *s = (shape *)0; uint32_t max = 0u; uint32_t i; for (i = 0u; i max) { max = area; s = shapes[i]; } } return s;}void drawallshapes(shape const *shapes[], uint32_t nshapes) { uint32_t i; for (i = 0u; i super, x, y); // 调用基类的构造函数 me->super.vptr = &vtbl; // 重载 vptr me->width = width; me->height = height;}// rectangle's 虚函数实现static uint32_t rectangle_area_(shape const * const me) { rectangle const * const me_ = (rectangle const *)me; //显示的转换 return (uint32_t)me_->width * (uint32_t)me_->height;}static void rectangle_draw_(shape const * const me) { rectangle const * const me_ = (rectangle const *)me; //显示的转换 printf(rectangle_draw_(x=%d,y=%d,width=%d,height=%d), shape_getx(me), shape_gety(me), me_->width, me_->height);}
5.4 虚函数调用
有了前面虚表(virtual tables)和虚指针(virtual pointers)的基础实现,虚拟调用(后期绑定)就可以用下面代码实现了。
uint32_t shape_area(shape const * const me){ return (*me->vptr->area)(me);} 这个函数可以放到.c文件里面,但是会带来一个缺点就是每个虚拟调用都有额外的调用开销。为了避免这个缺点,如果编译器支持内联函数(c99)。我们可以把定义放到头文件里面,类似下面:static inline uint32_t shape_area(shape const * const me) { return (*me->vptr->area)(me);} 如果是老一点的编译器(c89),我们可以用宏函数来实现,类似下面这样:#define shape_area(me_) ((*(me_)->vptr->area)((me_))) 看一下例子中的调用机制: 5.5 main.c#include rect.h #include circle.h #include int main() { rectangle r1, r2; circle c1, c2; shape const *shapes[] = { &c1.super, &r2.super, &c2.super, &r1.super }; shape const *s; // 实例化矩形对象 rectangle_ctor(&r1, 0, 2, 10, 15); rectangle_ctor(&r2, -1, 3, 5, 8); // 实例化圆形对象 circle_ctor(&c1, 1, -2, 12); circle_ctor(&c2, 1, -3, 6); s = largestshape(shapes, sizeof(shapes)/sizeof(shapes[0])); printf(largetsshape s(x=%d,y=%d), shape_getx(s), shape_gety(s)); drawallshapes(shapes, sizeof(shapes)/sizeof(shapes[0])); return 0;}输出结果:largetsshape s(x=1,y=-2)circle_draw_(x=1,y=-2,rad=12)rectangle_draw_(x=-1,y=3,width=5,height=8)circle_draw_(x=1,y=-3,rad=6)rectangle_draw_(x=0,y=2,width=10,height=15)
总结
还是那句话,面向对象编程是一种方法,并不局限于某一种编程语言。用 c 语言实现封装、单继承,理解和实现起来比较简单,多态反而会稍微复杂一点,如果打算广泛的使用多态,还是推荐转到 c++ 语言上,毕竟这层复杂性被这个语言给封装了,你只需要简单的使用就行了。但并不代表,c 语言实现不了多态这个特性。
主动降噪无线蓝牙耳机有哪些?20年降噪无线耳机推荐
星纵智能LoRa解决方案在农业中的不同应用
直线马达助力的悬挂式空中轨道列车试乘发车
通过协同仿真改善高速开关电源的设计
华为智能数据中心的解决方案后发先制 为用户实现利益价值最大化
C语言实现面向对象的方法
区块链人才为什么供需不平衡
9coin,助您轻松赚取“睡后”收入
空气监测微型站是什么
特斯拉对购买Model 3和Model Y买家免费增压
40个Nginx常问面试题
华为云大数据BI,企业数字化运营得力助手
新的热量模型可以帮助医疗电子设备持续更长时间
不同的通信系统有什么不同
STM32复位来源 以及系统和内核复位区别
!销售/回收E3633A电源E3633A小兵/孟S13825
新一代徕卡双摄+多种配色,逆天神机华为P10
6388元的第一款双摄iPhone7 Plus,光学防抖+防水防尘!
专用IC解密技术AVR应用技巧
软件巨头正在终止Lumia Offers应用程序