不知道有多少人去了解过语言的发展史,早期C语言的语法功能其实比较简单。随着应用需求和场景的变化,C语言的语法功能在不断升级变化。 # _4 H0 W( a' R! o
虽然我们的教材有这么一个结论:C语言是面向过程的语言,C++是面向对象的编程语言,但面向对象的概念是在C语言阶段就有了,而且应用到了很多地方,比如某些操作系统内核、通信协议等。
# r1 |% p7 M k' v
面向对象编程,也就是大家说的OOP(Object Oriented Programming)并不是一种特定的语言或者工具,它只是一种设计方法、设计思想,它表现出来的三个最基本的特性就是封装、继承与多态。
. N& P$ p! `# j- x: W; ]& V1 为什么要用C语言实现面向对象2 v# Z) X; v& v- Q4 C
阅读文本之前肯定有读者会问这样的问题:我们有C++面向对象的语言,为什么还要用C语言实现面向对象呢? 6 k9 m1 r0 H4 ~& b: Q6 e) L2 n1 T
C语言这种非面向对象的语言,同样也可以使用面向对象的思路来编写程序的。只是用面向对象的C++语言来实现面向对象编程会更简单一些,但是C语言的高效性是其他面向对象编程语言无法比拟的。
3 z- K3 ^+ |: F( a# k! j7 L4 H
当然使用C语言来实现面向对象的开发相对不容易理解,这就是为什么大多数人学过C语言却看不懂Linux内核源码。
E7 c$ U8 B' i6 w. k/ t
所以这个问题其实很好理解,只要有一定C语言编程经验的读者都应该能明白:面向过程的C语言和面向对象的C++语言相比,代码运行效率、代码量都有很大差异。在性能不是很好、资源不是很多的MCU中使用C语言面向对象编程就显得尤为重要。 0 k# _3 K5 b1 j; Q
2 具备条件
. \+ d, ~& g, {/ b$ y
要想使用C语言实现面向对象,首先需要具备一些基础知识。比如:(C语言中的)结构体、函数、指针,以及函数指针等,(C++中的)基类、派生、多态、继承等。
1 x2 m( S& }! @, N
首先,不仅仅是了解这些基础知识,而是有一定的编程经验,因为上面说了“面向对象是一种设计方法、设计思想”,如果只是停留在字面意思的理解,没有这种设计思想肯定不行。
* W0 V0 n- e0 z( U
因此,不建议初学者使用C语言实现面向对象,特别是在真正项目中。建议把基本功练好,再使用。
+ Q% Z; ]+ b# _3 n4 q5 g
利用C语言实现面向对象的方法很多,下面就来描述最基本的封装、继承和多态。
, R, s! N+ y$ r |+ y9 r- U+ o3 封装
3 \8 _6 i& P7 I+ }
封装就是把数据和函数打包到一个类里面,其实大部分C语言编程者都已近接触过了。 % S) I9 f. }9 k6 n8 H! H; o; h
C 标准库中的 fopen(), fclose(), fread(), fwrite()等函数的操作对象就是 FILE。数据内容就是 FILE,数据的读写操作就是 fread()、fwrite(),fopen() 类比于构造函数,fclose() 就是析构函数。
. H" `9 }; A0 r0 x" @8 D8 v
这个看起来似乎很好理解,那下面我们实现一下基本的封装特性。 - ) X4 t* J" j( @% Z9 f( ^& B
- #ifndef SHAPE_H# o) n0 i2 [4 m& `
- #define SHAPE_H
8 t* d. n: ^0 p* ^, u/ J - 1 p1 N" F4 Q7 Q) s9 X4 P% U! n# F
- #include <stdint.h> \& S7 J+ s0 A. a: C* c8 }) K$ E" A
- - t( y. e- l+ f
- // Shape 的属性
' O: }" f; H9 {) } - typedef struct {6 y" u+ t- D( |9 Y; o) Y
- int16_t x; " S1 Y) t+ k8 Q- Q9 e& U
- int16_t y;
; U6 ^, v- q3 z @( f - } Shape;/ U1 ~6 H; k( d" f. Y ?6 r* ^5 C
# B- q4 c/ @: C0 O: A" [- // Shape 的操作函数,接口函数
: @" ^0 G/ r* G& c7 w - void Shape_ctor(Shape * const me, int16_t x, int16_t y);0 G5 o9 e e9 I. g/ S" j
- void Shape_moveBy(Shape * const me, int16_t dx, int16_t dy);
3 t5 `3 J7 ^; n- {; [( W - int16_t Shape_getX(Shape const * const me);
# E' C5 e3 O9 @# W( @1 r - int16_t Shape_getY(Shape const * const me);9 A& z; P( w" |( f% n
4 H. C6 m' x+ e$ _8 j G/ W- #endif /* SHAPE_H */
复制代码# G4 h& Z7 q) y3 _% z" u
这是 Shape 类的声明,非常简单,很好理解。一般会把声明放到头文件里面 “Shape.h”。来看下 Shape 类相关的定义,当然是在 “Shape.c” 里面。
1 ~/ Z) W% ]/ X) C; i3 g; ]& ^- #include "shape.h"! K. ~! ]2 l1 ?: Y
- % c5 i, W' Z2 z; O# v; r
- // 构造函数
$ u4 z$ ]& l$ V# r - void Shape_ctor(Shape * const me, int16_t x, int16_t y)
' F, I0 V( @/ b/ E( f) u V - {
, _* l4 s. ^/ O7 q - me->x = x;
) d, ~5 b& ?9 i! n2 g f9 M - me->y = y;
& W& y/ h+ U' l. c- _( B& b - }: T! ], s/ b' z% r$ y& i( h8 O
4 ]: J4 o1 w( [ E) `' l- B- void Shape_moveBy(Shape * const me, int16_t dx, int16_t dy)
7 Y* [: Y6 }( c, @7 P A* q' p - {
7 M% j0 j o+ C; l' U7 S8 ~ - me->x += dx;
$ b+ {4 r' q% b2 n - me->y += dy;
}' W8 f7 J# D. l5 F - }
7 B5 z( W$ z" W. c! | - 4 M( i- t7 d" V! W
- // 获取属性值函数/ j: w! I+ `5 V9 r( W
- int16_t Shape_getX(Shape const * const me) 1 k$ N3 H3 K2 r% V. D
- {
& o# b( T2 c- S: }5 V! d; A - return me->x;
: l) a5 y! {% ]) I - }$ m! M5 b$ S9 d1 P( ^
- int16_t Shape_getY(Shape const * const me) 5 t3 k+ a8 I* X# k8 D! W8 Q- X& ]" N
- {
: {5 d+ T' S% |/ @; Q2 | - return me->y;6 M* `1 \ e5 [$ c
- }
复制代码
0 E8 f& X5 W$ `& _4 i再看下 main.c- 9 N$ [! D$ J% ?$ K
- #include "shape.h" /* Shape class interface */0 W. h3 r4 L3 v1 T1 ?7 m6 B# P
- #include <stdio.h> /* for printf() */
6 P* ]( |/ e& q/ ` [ - 5 f$ F) |& W* w( u. d3 d2 z4 A
- int main() ( f! j) Q9 J$ k, ]. l
- {
/ m, R/ S, O& A, D1 K& @0 S - Shape s1, s2; /* multiple instances of Shape */
/ u6 y0 a( @9 P, m; Z9 V; J
$ D; p* j. j9 O& |- @- Shape_ctor(&s1, 0, 1);$ _% O2 T a+ l S$ G! f
- Shape_ctor(&s2, -1, 2);
8 G9 A/ W+ B x. | - 6 T. x* V) d; ?1 x r! D# y9 ], e
- printf("Shape s1(x=%d,y=%d)\n", Shape_getX(&s1), Shape_getY(&s1));
* w$ @/ ~2 p+ Z- ` l3 Y, l' A' J4 J - printf("Shape s2(x=%d,y=%d)\n", Shape_getX(&s2), Shape_getY(&s2));
2 c7 u% J8 v) P( `3 u9 J+ q
; H4 f- c: r: `$ N& Q- Shape_moveBy(&s1, 2, -4);4 L- a: K5 v+ J
- Shape_moveBy(&s2, 1, -2);. n) f- a( j& S* Y2 u
- ' A( J$ N, B6 a( E3 J/ R
- printf("Shape s1(x=%d,y=%d)\n", Shape_getX(&s1), Shape_getY(&s1));
! o4 a% P! p! J' l# Z3 a5 h - printf("Shape s2(x=%d,y=%d)\n", Shape_getX(&s2), Shape_getY(&s2));
w d. M% V4 V- d& a* G - ! o9 l6 J) f1 J" s$ c5 ^4 Z$ s
- return 0;# \, |1 J) J! _( y& `+ I' s Y
- }
复制代码
2 H0 W: q5 P# Z$ z7 [4 t编译之后,看看执行结果:- 4 s5 ~6 e5 X* R; g
- Shape s1(x=0,y=1)# [9 c( ?0 p, q. e2 g
- Shape s2(x=-1,y=2)
# V4 ~! e" k; t" n9 o - Shape s1(x=2,y=-3)
# y0 J, a# e. B - Shape s2(x=0,y=0)
复制代码 : K" |0 B# o7 I; k4 u2 R8 o& Y7 ]( [
整个例子,非常简单,非常好理解。以后写代码时候,要多去想想标准库的文件IO操作,这样也有意识的去培养面向对象编程的思维。
9 t& ^! j* T/ y5 V4 继承
$ Y' G' N( |& N0 J" e( h2 b# U% m
继承就是基于现有的一个类去定义一个新类,这样有助于重用代码,更好的组织代码。在 C 语言里面,去实现单继承也非常简单,只要把基类放到继承类的第一个数据成员的位置就行了。 2 u# V$ q3 |7 q0 f4 e+ d
例如,我们现在要创建一个 Rectangle 类,我们只要继承 Shape 类已经存在的属性和操作,再添加不同于 Shape 的属性和操作到 Rectangle 中。
2 m/ t1 n: _4 a0 t! P& {: _
下面是 Rectangle 的声明与定义: - + W" f) a9 u$ Y
- #ifndef RECT_H
2 R8 {$ V( @* J, ~& `6 ^* r - #define RECT_H
, c1 s0 p9 i* W+ W5 y8 Y - 8 C* T/ r1 L$ L( q, L
- #include "shape.h" // 基类接口
8 w5 e! e2 ~4 h" C8 B8 j3 t - % X6 d7 \* h! g, I! W" U
- // 矩形的属性 u5 S+ O7 |; W, R; X! u& _3 T
- typedef struct {- d) i! V/ R S [
- Shape super; // 继承 Shape
* d: O& B! E+ L - 9 B x$ S. E0 o7 c
- // 自己的属性
7 G9 [' _( J+ Z# F8 I0 ] - uint16_t width;* m/ @- u3 x% c ^" ], F' ?
- uint16_t height;% \" M' g; b% v$ ?: \0 n
- } Rectangle;# N( `- P) n, a2 j) m& h; k
+ {0 _+ d7 q+ y& \! P0 K) _( o- // 构造函数0 {$ X! Z2 K- i6 Q8 J; c
- void Rectangle_ctor(Rectangle * const me, int16_t x, int16_t y,
6 F ?+ ?' I' e1 D - uint16_t width, uint16_t height);
' H; k* Q9 Q, d9 c( a6 I5 T3 k* d& U- W( Q
( K6 M2 B* f6 H% R/ H- #endif /* RECT_H */
复制代码
! B' c" m% W' T, w, [" [7 S) x+ a* V- #include "rect.h"$ r* K1 p7 m2 J
- ) a4 T) q- _4 x4 }
- // 构造函数2 z5 R9 ` p& I7 m0 D `) a
- void Rectangle_ctor(Rectangle * const me, int16_t x, int16_t y,2 h; O( e; ^+ c! i& ^
- uint16_t width, uint16_t height)
3 W/ q! N4 ?/ W0 B - {* A9 [1 K( W+ ?' k; G1 C& v
- /* first call superclass’ ctor */
9 p2 D* r) m" R8 c7 c$ [ - Shape_ctor(&me->super, x, y);
. v8 a# d5 R% T- g( T& j% z) W
4 U* t( x- B9 h" L- /* next, you initialize the attributes added by this subclass... */( ?% }/ R# o+ S' C ~2 u
- me->width = width;
5 }0 t$ q2 H3 d" b% Y - me->height = height;
% X$ Q6 ?! b) U% P# S7 }" \ - }
复制代码; I0 {7 W( j1 X; q8 a
我们来看一下 Rectangle 的继承关系和内存布局:
' y8 e" R: A/ y1 N+ G R
因为有这样的内存布局,所以你可以很安全的传一个指向 Rectangle 对象的指针到一个期望传入 Shape 对象的指针的函数中,就是一个函数的参数是 “Shape *”,你可以传入 “Rectangle *”,并且这是非常安全的。这样的话,基类的所有属性和方法都可以被继承类继承! - $ |; e: K: @0 }; r1 V
- #include "rect.h" - ]. |% X& n; J: ~: ?6 @
- #include <stdio.h>
5 w1 K$ @: i) r* z5 T
! ]% \7 B/ K3 F. W- int main()
9 x9 j; S5 d) Y8 s - {1 t# J3 w7 g$ l
- Rectangle r1, r2;
4 \! X* @0 L% q. F8 h* A2 n - 7 Y s9 p! B4 [. R, V
- // 实例化对象
# e# [, U) N+ K U: }: L - Rectangle_ctor(&r1, 0, 2, 10, 15);
; q) \3 C* o7 o9 E v: i - Rectangle_ctor(&r2, -1, 3, 5, 8);
6 w6 K/ S: W# e) K
; ~, b# ^' a, g$ L/ y8 [! z6 d& y- printf("Rect r1(x=%d,y=%d,width=%d,height=%d)\n",0 L) N( D7 r3 ]1 ^$ Z, q; f
- Shape_getX(&r1.super), Shape_getY(&r1.super),
( d. t v9 d4 R* c9 {$ o6 n/ k$ J - r1.width, r1.height);
0 y7 j+ [- ]2 X# ?3 W7 O( I: W - printf("Rect r2(x=%d,y=%d,width=%d,height=%d)\n",
( l9 J- a; D5 ]- U& i* |! P. Y - Shape_getX(&r2.super), Shape_getY(&r2.super),
7 T5 z$ r4 n& p* J/ E: A - r2.width, r2.height);
( a6 l9 I1 Z/ ]! w, M4 x. ? - : s) l' }) E2 t
- // 注意,这里有两种方式,一是强转类型,二是直接使用成员地址% c0 u* h/ k2 V5 z/ M9 P
- Shape_moveBy((Shape *)&r1, -2, 3);$ S- W" Z/ k. ]" ]- `6 x5 s
- Shape_moveBy(&r2.super, 2, -1);9 I& Y* m% R9 I% p$ M) \$ F+ C/ e
- 7 J5 X! f+ _* ?. D* ~& e3 ]# `9 ~
- printf("Rect r1(x=%d,y=%d,width=%d,height=%d)\n",
4 R' m; l! g, ? - Shape_getX(&r1.super), Shape_getY(&r1.super),- j: ]" K7 U& ]1 C& t1 I$ j
- r1.width, r1.height);
. p5 \4 W' k. ~8 S% ? - printf("Rect r2(x=%d,y=%d,width=%d,height=%d)\n",0 R) _' \! ^; j8 a! V6 f. j x
- Shape_getX(&r2.super), Shape_getY(&r2.super),
' @# ~, U. m* r: h- Z5 ^* c- j - r2.width, r2.height);
$ z* u) p2 O1 Y5 P) y" u9 w) I
7 M$ C2 T: N7 s- return 0;2 G$ \- Y; v6 A& z5 F* i
- }
复制代码
% U/ u6 `$ S/ S9 a9 ~
输出结果:
& V9 U6 W& M4 c4 b0 T
7 w2 P$ s' l7 p- Rect r1(x=0,y=2,width=10,height=15)1 F3 X; Q% S# U+ I# H0 M
- Rect r2(x=-1,y=3,width=5,height=8)7 L0 d, g o/ r' {
- Rect r1(x=-2,y=5,width=10,height=15)
8 U8 l* {6 }! x- L" B- `+ I) t - Rect r2(x=1,y=2,width=5,height=8)
复制代码 + Z& m: T/ w/ W- S9 {
5 多态7 `5 V0 i3 L; ]& p
C++ 语言实现多态就是使用虚函数。在 C 语言里面,也可以实现多态。( K1 g2 Z. L: L2 a# ]
现在,我们又要增加一个圆形,并且在 Shape 要扩展功能,我们要增加 area() 和 draw() 函数。但是 Shape 相当于抽象类,不知道怎么去计算自己的面积,更不知道怎么去画出来自己。而且,矩形和圆形的面积计算方式和几何图像也是不一样的。7 K/ M- J1 T; q
下面让我们重新声明一下 Shape 类:- , }2 `- ?( [1 T& j. Q: [$ N$ p
- #ifndef SHAPE_H
5 @2 k8 V# B$ p. r* o, O7 _ - #define SHAPE_H; \4 K6 b) W" N$ Z* \& E
5 b) p/ r% _5 T) E( M- #include <stdint.h>1 X( B& \6 f x6 u! n# S
- 6 d( V9 G, G7 s* e
- struct ShapeVtbl;- |4 o `' P& c1 v$ c6 H! g# T% [0 Y. v
- // Shape 的属性, X; |) r# i* b* R5 _8 O4 x
- typedef struct {
8 w( ]4 }" a8 g6 g4 S6 z - struct ShapeVtbl const *vptr;
* y" Z$ ]7 D% z, a/ B( c - int16_t x;
) S7 U$ m& t/ U% h& h - int16_t y; 5 {1 s* q. \; P4 p$ [
- } Shape;8 b( w6 i; Q, e9 |
- , \ l, b2 e' z+ a: R* ]7 b6 m" \& O8 W6 ]
- // Shape 的虚表% Z+ \7 H# f4 T8 p5 y: H/ [! K
- struct ShapeVtbl {* a4 n% J6 H E
- uint32_t (*area)(Shape const * const me);
( G9 w6 u6 q% Q7 p/ n; a4 h - void (*draw)(Shape const * const me);
6 f0 N0 A( ?; {" [; r - };- a: o; R9 o9 {$ F: g4 X! s/ O5 q& ?- N
/ C% U$ [2 z! ]. k, p- // Shape 的操作函数,接口函数
' }: m" E" X* d - void Shape_ctor(Shape * const me, int16_t x, int16_t y);/ y" ?8 ^( q0 t" _' Z7 q& w0 k: y
- void Shape_moveBy(Shape * const me, int16_t dx, int16_t dy);
: F7 g- }0 J+ {/ F& y4 S& c R& e - int16_t Shape_getX(Shape const * const me);! b) o: ?6 V- A8 S& X; J& B
- int16_t Shape_getY(Shape const * const me);' Z; p: E" p- ]9 x6 R5 F
% b, H. l" u( o2 D/ S9 o- static inline uint32_t Shape_area(Shape const * const me) # Q% Z3 x4 i: g. m+ P6 v/ n7 e
- {( D' z) G" h8 `, f" p) n: R# L
- return (*me->vptr->area)(me);: c/ @7 }) a% k+ t$ |
- }
6 E' r9 S, ?! x8 T9 ^ - " C+ B7 Q0 E) K) J; y+ p
- static inline void Shape_draw(Shape const * const me)
5 r) f# x9 D$ ?' z% H5 z, ] - {
' \; v1 H) _1 D* |& Y9 o, g/ j - (*me->vptr->draw)(me);
- c; B# G# L) C - }
. } l' E) ?% T" ^: N
& h$ @) k) Y) h2 ` N7 R- 7 Z% ?9 f+ _: G! U# p% M
- Shape const *largestShape(Shape const *shapes[], uint32_t nShapes);' v* G- Z* j- H3 Q) u" E
- void drawAllShapes(Shape const *shapes[], uint32_t nShapes);
: E3 Y8 `% h$ C8 ], Y+ f - : h. l+ z1 F- n. I$ z+ a/ W2 T
- #endif /* SHAPE_H */
复制代码5 I0 L2 E# }- ]8 D
看下加上虚函数之后的类关系图:+ t' `) C% z/ F4 M1 m0 z1 p
; n9 ?+ p( Y+ V8 O$ F( ~% M 5.1 虚表和虚指针虚表(Virtual Table)是这个类所有虚函数的函数指针的集合。
4 I; a9 u6 y9 w! C; x, S7 J虚指针(Virtual Pointer)是一个指向虚表的指针。这个虚指针必须存在于每个对象实例中,会被所有子类继承。
8 D; J+ A& U; G. E" J) F在《Inside The C++ Object Model》的第一章内容中,有这些介绍。# H: i. L2 o1 L* m
5.2 在构造函数中设置vptr在每一个对象实例中,vptr 必须被初始化指向其 vtbl。最好的初始化位置就是在类的构造函数中。事实上,在构造函数中,C++ 编译器隐式的创建了一个初始化的vptr。在 C 语言里面, 我们必须显示的初始化vptr。, N$ L. c2 U, b% w: ^+ `
下面就展示一下,在 Shape 的构造函数里面,如何去初始化这个 vptr。- " V* L3 J# v) [1 [
- #include "shape.h". _5 @+ T2 ^! K& e
- #include <assert.h>
' z5 k3 `* ^7 \% I - 0 P- o9 j* T) T# Y4 H
- // Shape 的虚函数
5 E, r9 B" X J* e - static uint32_t Shape_area_(Shape const * const me);/ ?' \0 |1 {8 v/ y
- static void Shape_draw_(Shape const * const me);
( p, P r h( @
" p% x. A* _) x6 ^" l: f- // 构造函数
4 ^) Z3 g" f" d: T: ?5 u - void Shape_ctor(Shape * const me, int16_t x, int16_t y) % Z' S" S8 |% ?- Z0 V" ?
- {
5 j5 r& v3 r. B2 K5 ] - // Shape 类的虚表
3 a. s( [# V% `8 ^0 Y - static struct ShapeVtbl const vtbl = " r ~, C1 x5 }" Y
- { 8 A. }) D W. ?% k
- &Shape_area_,
E, L2 V2 M0 h& e, ?% [: ~ - &Shape_draw_: w1 i/ K7 ~! y/ ^1 T- z% R; ^
- };3 n5 A' g# O( X) l+ h8 l
- me->vptr = &vtbl;
, f0 s) Z" r; m' L$ s/ W - me->x = x;6 k( k" D) F; J. Q/ @" x
- me->y = y;9 j8 w# x2 b' u$ D
- } m% Q' s/ a. I' z/ p
- . U+ f& j0 k2 {5 J! M& U
0 W7 U& G. i: v4 m: m# G- void Shape_moveBy(Shape * const me, int16_t dx, int16_t dy)
/ i! Q" _) S9 g) k% ?' Z! p; t - {
- `- `7 _, s( | - me->x += dx;# q$ S8 ` A! v; V0 k6 `
- me->y += dy;+ l! ^% `9 [+ o7 [; {) }2 Z: L
- }; `2 `. |: [3 d
- A9 X2 u* D- C" `5 b6 a0 k
7 h; s! U4 P$ |. P- int16_t Shape_getX(Shape const * const me)
# ^7 y$ N3 W6 I3 N/ T - {5 {, h% {4 n) }. O+ Y$ E* L$ h
- return me->x;
: K" U+ @" _1 v. V- V - }, D4 P S# A/ j1 W+ i. U2 Q- L2 D
- int16_t Shape_getY(Shape const * const me) 8 }" W3 O; @1 B+ A4 D
- {7 k* ]4 J2 q2 V# h9 m/ U: A2 x
- return me->y;2 I N: {4 }* Z# u d$ V
- }$ |* S, M3 s5 k2 I
- / }& u& x3 _8 Q
- // Shape 类的虚函数实现5 e" y& ?, N. p! ]5 u/ l
- static uint32_t Shape_area_(Shape const * const me) ' b" B6 }, n7 |4 ^& { X- X
- {$ B2 g; y. K$ Y7 O
- assert(0); // 类似纯虚函数$ D. ?1 e2 I& ?3 L! ?$ R. C
- return 0U; // 避免警告& O& d+ Y+ c1 H0 M! y' E
- }
- ^; w. e1 B+ ~3 s, ~( e9 Y V
; x+ A+ o, K# Z/ W- static void Shape_draw_(Shape const * const me)
2 k8 [. p! i. R6 G% G - {
6 I3 ~4 p* F0 g Z) u - assert(0); // 纯虚函数不能被调用' T+ G1 Y. s0 I6 k8 X9 D- r8 h
- }
3 c5 a5 _! B1 B' E5 N
8 N0 {: p, V3 e8 _0 u* S- $ w) ?, j7 |, S
- Shape const *largestShape(Shape const *shapes[], uint32_t nShapes) ' i' J7 l0 x# x% X" ^' M0 ?
- {
f& K1 p! H" D9 J, g0 X - Shape const *s = (Shape *)0;1 D+ J) L$ A5 w( i: b
- uint32_t max = 0U;) s$ }7 J* U$ F) h z
- uint32_t i;* u0 l2 r/ m( k$ W$ J4 {+ i
- for (i = 0U; i < nShapes; ++i)
! m( y. r7 @1 G; Q) Q- M - {
) K1 s9 L8 A5 i - uint32_t area = Shape_area(shapes[i]);// 虚函数调用6 p9 ^& ^$ S5 Z; m4 U
- if (area > max)
( e2 Q) f; T2 Y' l/ F - {
2 \( C# u; ` J8 m% v, l - max = area;
7 s' @8 A: L8 B8 e: x - s = shapes[i];
' [+ @5 w5 o6 D* }0 ~6 n - }
0 T, y) I$ N6 `( D+ o - }
1 E+ \& a6 _! B8 G - return s;
0 W9 j! X5 G5 }2 G {, T5 g - }1 G( X8 K6 u1 r( f
( u% ]& r) V ^9 Y, {- ' @4 |# @( A) g( a- D
- void drawAllShapes(Shape const *shapes[], uint32_t nShapes) " o, I8 Y& z- Z1 s
- {
' l& G0 A$ n9 b3 ^$ Z - uint32_t i;6 l- e r2 a0 `1 r5 I
- for (i = 0U; i < nShapes; ++i)
# W% ^' _) I$ `& V" s - {; ~( c7 z5 R& _! X
- Shape_draw(shapes[i]); // 虚函数调用
! Y9 r/ D3 @8 M0 ? - }
* {" m0 [9 [) l' z" f - }
复制代码
1 `; ?8 K5 }; O. q5.3 继承 vtbl 和 重载 vptr上面已经提到过,基类包含 vptr,子类会自动继承。但是,vptr 需要被子类的虚表重新赋值。并且,这也必须发生在子类的构造函数中。下面是 Rectangle 的构造函数。 - ) v+ Y# b4 _9 t2 ?/ ]
- #include "rect.h"
3 k- {" ]" ~# m* @ - #include <stdio.h> 6 q7 D4 q1 a+ X, [) Y
' K9 B+ P( Z3 U- // Rectangle 虚函数
2 w" t) @! G3 p4 { - static uint32_t Rectangle_area_(Shape const * const me);
# V w' C* a7 s - static void Rectangle_draw_(Shape const * const me);% d6 J! i, F$ D( V f6 b
; m N; Y' d* n. R6 T+ X& Y* A- // 构造函数
, o9 j, l! P1 C; k$ T; P! G0 S - void Rectangle_ctor(Rectangle * const me, int16_t x, int16_t y,0 p K: C' K/ o( o) i
- uint16_t width, uint16_t height)
# ?5 S% g& p r- j0 L1 X8 P: N5 d - {# X2 m$ ?5 F) z
- static struct ShapeVtbl const vtbl =
: A( g. [9 \& g) H - {
c0 F: H: i& _" l: A) t - &Rectangle_area_,
% @; t) L9 T/ H' i3 r0 X - &Rectangle_draw_4 h9 X3 ^1 L* _! |: M
- };
/ v; R' W( {/ v3 R! k& ~! S& Y - Shape_ctor(&me->super, x, y); // 调用基类的构造函数4 ^6 q* }/ X- } D
- me->super.vptr = &vtbl; // 重载 vptr
' |, M9 \3 }. M3 q! H, m - me->width = width;. W, h9 Y8 {/ C6 A
- me->height = height;0 _0 [3 j- p4 m# D( z
- }
- y; w8 e2 I3 C1 Y7 O
- K/ w# Q( N( }* x& f/ l& j- // Rectangle's 虚函数实现2 K* B6 }0 Z# H& U2 \( C2 L8 @
- static uint32_t Rectangle_area_(Shape const * const me) 2 X2 l5 [. x3 p( }$ G9 Q
- {7 E% x6 i9 O9 d5 z: K7 F- z
- Rectangle const * const me_ = (Rectangle const *)me; //显示的转换
0 O* |# ~ W0 S8 O3 w( P4 g$ } - return (uint32_t)me_->width * (uint32_t)me_->height;
9 @, ^/ B; C! U+ c) i/ J( L$ | - }' b( x$ r+ y% w- z
) ]$ f: _! A, i/ x- C3 e ^- static void Rectangle_draw_(Shape const * const me) 5 f- `7 q+ L% y4 J$ o8 ]" r; |
- {
$ _5 J# s: K& D9 z( m* I- O1 l. c - Rectangle const * const me_ = (Rectangle const *)me; //显示的转换
$ N8 v& B, N+ ?9 @6 |. A* `0 `- e0 T - printf("Rectangle_draw_(x=%d,y=%d,width=%d,height=%d)\n",! k6 j6 h, {' c% R* \# v1 ?
- Shape_getX(me), Shape_getY(me), me_->width, me_->height);
' Y/ ]) ]0 B3 z6 N( { - }
复制代码
! D- P% V7 N, K' u3 \% b, _ 5.4 虚函数调用有了前面虚表(Virtual Tables)和虚指针(Virtual Pointers)的基础实现,虚拟调用(后期绑定)就可以用下面代码实现了。 - 2 y+ \+ s V/ C9 N/ B
- uint32_t Shape_area(Shape const * const me)
- D' S& i C( b - {
' |2 R+ p, s. e" J* K+ J7 G5 Z6 f - return (*me->vptr->area)(me);& F) x7 b5 P* V
- }
复制代码 4 G: r% a) {- N- z }
这个函数可以放到.c文件里面,但是会带来一个缺点就是每个虚拟调用都有额外的调用开销。为了避免这个缺点,如果编译器支持内联函数(C99)。我们可以把定义放到头文件里面,类似下面:- # S$ F' i K5 z8 N. F
- static inline uint32_t Shape_area(Shape const * const me) . G0 o; w4 D+ ?+ x
- {! G/ t( f" D& V2 k( `
- return (*me->vptr->area)(me);
0 Y; k8 |1 N0 z - }
复制代码 2 ]# j" i$ s% j- n' d1 k% E
如果是老一点的编译器(C89),我们可以用宏函数来实现,类似下面这样:- #define Shape_area(me_) ((*(me_)->vptr->area)((me_)))
# f. N$ y8 E4 k; k6 ~ 看一下例子中的调用机制:
/ l- ]3 N) n# J# B" J
5.5 main.c
/ W0 _" T( V( d- #include "rect.h"
/ m. e" b T A- ] - #include "circle.h"
) c, @( f$ V1 l - #include <stdio.h>
0 B" i5 y" h ]3 ^1 [4 _6 H - " j7 q! t9 [3 h7 u" B/ X* Z; j& Z
- int main() 3 B. v7 ]. K- J0 G3 C
- {
4 k) g) t2 V. N9 k( U1 B2 Q - Rectangle r1, r2; 6 R+ m+ |6 s: l! W
- Circle c1, c2;
/ L f* P. f* q$ f5 A r - Shape const *shapes[] = + F! }- _: ~# R. R/ G E8 F
- {
6 U# w4 Q V" [ - &c1.super,
0 ~( B# N2 m! p& ?/ T3 q0 g( I; l - &r2.super,1 p1 | D6 W. w2 i5 _ U" J. s
- &c2.super,: R. a! |1 O/ ]! `. L5 y" @( Y
- &r1.super
6 O9 C2 v" e1 F8 V( f8 K - };
u, H o( i4 } - Shape const *s;
% B% e% D8 m/ W- [7 | - ; f Z% D& `/ K( x5 }
- // 实例化矩形对象; ^' @2 N% c, H4 ]9 `
- Rectangle_ctor(&r1, 0, 2, 10, 15);& A6 I$ s, }+ Q# b
- Rectangle_ctor(&r2, -1, 3, 5, 8);
: f( ^8 |0 {# h t; f; L d L, m
2 L; {# A+ z+ n+ Q4 ^- // 实例化圆形对象
+ ~0 L8 f+ C9 I- n4 U& s5 o - Circle_ctor(&c1, 1, -2, 12);
! Z& r1 q5 X$ f G - Circle_ctor(&c2, 1, -3, 6);, g' S5 V' [' n
- ' A4 a, F4 _, u, ? d0 w5 q
- s = largestShape(shapes, sizeof(shapes)/sizeof(shapes[0]));0 o' t5 u/ ^& o5 Y
- printf("largetsShape s(x=%d,y=%d)\n", Shape_getX(s), Shape_getY(s));
$ G8 u5 N9 P8 |$ W5 W
) t4 }+ v" K2 ? J( J. P5 S; W$ |- drawAllShapes(shapes, sizeof(shapes)/sizeof(shapes[0]));- ^: @! C. D9 f6 Z% I& a9 S
- " v2 _3 w. {. C7 T
- return 0;# f7 y% t; }6 G* G, ^8 @- a( O
- }
复制代码 输出结果:- 2 V: F! x# D% f! g$ s
- largetsShape s(x=1,y=-2)
6 H [) }% ^+ G4 V - Circle_draw_(x=1,y=-2,rad=12)) K/ \& j) K4 I" i
- Rectangle_draw_(x=-1,y=3,width=5,height=8)
/ \: I% N- h7 N5 c+ L) B. _; m - Circle_draw_(x=1,y=-3,rad=6)
) i5 @. t: N2 @, H - Rectangle_draw_(x=0,y=2,width=10,height=15)
复制代码
/ w+ D2 m9 Y- j7 M; ]6 总结. R) k) F/ X6 \2 m0 ~# c$ y9 \4 B
还是那句话,面向对象编程是一种方法,并不局限于某一种编程语言。用 C 语言实现封装、单继承,理解和实现起来比较简单,多态反而会稍微复杂一点,如果打算广泛的使用多态,还是推荐转到 C++ 语言上,毕竟这层复杂性被这个语言给封装了,你只需要简单的使用就行了。但并不代表,C 语言实现不了多态这个特性。 |