C語言實(shí)現(xiàn)面向?qū)ο蟮姆椒ㄔ斀?/h1>
更新時(shí)間:2022年08月16日 14:07:39 作者:onlyshi
這篇文章主要為大家詳細(xì)介紹了C語言實(shí)現(xiàn)面向?qū)ο蟮姆椒?,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
1、引言
面向?qū)ο缶幊蹋∣OP)并不是一種特定的語言或者工具,它只是一種設(shè)計(jì)方法、設(shè)計(jì)思想。它表現(xiàn)出來的三個(gè)最基本的特性就是封裝、繼承與多態(tài)。很多面向?qū)ο蟮木幊陶Z言已經(jīng)包含這三個(gè)特性了,例如 Smalltalk、C++、Java。但是你也可以用幾乎所有的編程語言來實(shí)現(xiàn)面向?qū)ο缶幊?,例?ANSI-C。要記住,面向?qū)ο笫且环N思想,一種方法,不要太拘泥于編程語言。
2、封裝
封裝就是把數(shù)據(jù)和方法打包到一個(gè)類里面。其實(shí)C語言編程者應(yīng)該都已經(jīng)接觸過了,C 標(biāo)準(zhǔn)庫中的 fopen(), fclose(), fread(), fwrite()等函數(shù)的操作對象就是 FILE。數(shù)據(jù)內(nèi)容就是 FILE,數(shù)據(jù)的讀寫操作就是 fread()、fwrite(),fopen() 類比于構(gòu)造函數(shù),fclose() 就是析構(gòu)函數(shù)。這個(gè)看起來似乎很好理解,那下面我們實(shí)現(xiàn)一下基本的封裝特性。
#ifndef SHAPE_H
#define SHAPE_H
#include <stdint.h>
// Shape 的屬性
typedef struct {
int16_t x;
int16_t y;
} Shape;
// Shape 的操作函數(shù),接口函數(shù)
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 類相關(guān)的定義,當(dāng)然是在 “Shape.c” 里面。
#include "shape.h"
// 構(gòu)造函數(shù)
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;
}
// 獲取屬性值函數(shù)
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 <stdio.h> /* 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)\n", Shape_getX(&s1), Shape_getY(&s1));
printf("Shape s2(x=%d,y=%d)\n", Shape_getX(&s2), Shape_getY(&s2));
Shape_moveBy(&s1, 2, -4);
Shape_moveBy(&s2, 1, -2);
printf("Shape s1(x=%d,y=%d)\n", Shape_getX(&s1), Shape_getY(&s1));
printf("Shape s2(x=%d,y=%d)\n", Shape_getX(&s2), Shape_getY(&s2));
return 0;
}
編譯之后,看看執(zhí)行結(jié)果:
Shape s1(x=0,y=1)
Shape s2(x=-1,y=2)
Shape s1(x=2,y=-3)
Shape s2(x=0,y=0)
整個(gè)例子,非常簡單,非常好理解。以后寫代碼時(shí)候,要多去想想標(biāo)準(zhǔn)庫的文件IO操作,這樣也有意識的去培養(yǎng)面向?qū)ο缶幊痰乃季S。
3、繼承
繼承就是基于現(xiàn)有的一個(gè)類去定義一個(gè)新類,這樣有助于重用代碼,更好的組織代碼。在 C 語言里面,去實(shí)現(xiàn)單繼承也非常簡單,只要把基類放到繼承類的第一個(gè)數(shù)據(jù)成員的位置就行了。
例如,我們現(xiàn)在要?jiǎng)?chuàng)建一個(gè) Rectangle 類,我們只要繼承 Shape 類已經(jīng)存在的屬性和操作,再添加不同于 Shape 的屬性和操作到 Rectangle 中。
下面是 Rectangle 的聲明與定義:
#ifndef RECT_H
#define RECT_H
#include "shape.h" // 基類接口
// 矩形的屬性
typedef struct {
Shape super; // 繼承 Shape
// 自己的屬性
uint16_t width;
uint16_t height;
} Rectangle;
// 構(gòu)造函數(shù)
void Rectangle_ctor(Rectangle * const me, int16_t x, int16_t y,
uint16_t width, uint16_t height);
#endif /* RECT_H */
#include "rect.h"
// 構(gòu)造函數(shù)
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 的繼承關(guān)系和內(nèi)存布局

因?yàn)橛羞@樣的內(nèi)存布局,所以你可以很安全的傳一個(gè)指向 Rectangle 對象的指針到一個(gè)期望傳入 Shape 對象的指針的函數(shù)中,就是一個(gè)函數(shù)的參數(shù)是 “Shape *”,你可以傳入 “Rectangle *”,并且這是非常安全的。這樣的話,基類的所有屬性和方法都可以被繼承類繼承!
#include "rect.h"
#include <stdio.h>
int main()
{
Rectangle r1, r2;
// 實(shí)例化對象
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)\n",
Shape_getX(&r1.super), Shape_getY(&r1.super),
r1.width, r1.height);
printf("Rect r2(x=%d,y=%d,width=%d,height=%d)\n",
Shape_getX(&r2.super), Shape_getY(&r2.super),
r2.width, r2.height);
// 注意,這里有兩種方式,一是強(qiáng)轉(zhuǎn)類型,二是直接使用成員地址
Shape_moveBy((Shape *)&r1, -2, 3);
Shape_moveBy(&r2.super, 2, -1);
printf("Rect r1(x=%d,y=%d,width=%d,height=%d)\n",
Shape_getX(&r1.super), Shape_getY(&r1.super),
r1.width, r1.height);
printf("Rect r2(x=%d,y=%d,width=%d,height=%d)\n",
Shape_getX(&r2.super), Shape_getY(&r2.super),
r2.width, r2.height);
return 0;
}
輸出結(jié)果:
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)
4、多態(tài)
C++ 語言實(shí)現(xiàn)多態(tài)就是使用虛函數(shù)。在 C 語言里面,也可以實(shí)現(xiàn)多態(tài)。
現(xiàn)在,我們又要增加一個(gè)圓形,并且在 Shape 要擴(kuò)展功能,我們要增加 area() 和 draw() 函數(shù)。但是 Shape 相當(dāng)于抽象類,不知道怎么去計(jì)算自己的面積,更不知道怎么去畫出來自己。而且,矩形和圓形的面積計(jì)算方式和幾何圖像也是不一樣的。
下面讓我們重新聲明一下 Shape 類
#ifndef SHAPE_H
#define SHAPE_H
#include <stdint.h>
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 的操作函數(shù),接口函數(shù)
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 */
看下加上虛函數(shù)之后的類關(guān)系圖

4.1 虛表和虛指針
虛表(Virtual Table)是這個(gè)類所有虛函數(shù)的函數(shù)指針的集合。
虛指針(Virtual Pointer)是一個(gè)指向虛表的指針。這個(gè)虛指針必須存在于每個(gè)對象實(shí)例中,會被所有子類繼承。
在《Inside The C++ Object Model》的第一章內(nèi)容中,有這些介紹。
4.2 在構(gòu)造函數(shù)中設(shè)置vptr
在每一個(gè)對象實(shí)例中,vptr 必須被初始化指向其 vtbl。最好的初始化位置就是在類的構(gòu)造函數(shù)中。事實(shí)上,在構(gòu)造函數(shù)中,C++ 編譯器隱式的創(chuàng)建了一個(gè)初始化的vptr。在 C 語言里面, 我們必須顯示的初始化vptr。
下面就展示一下,在 Shape 的構(gòu)造函數(shù)里面,如何去初始化這個(gè) vptr。
#include "shape.h"
#include <assert.h>
// Shape 的虛函數(shù)
static uint32_t Shape_area_(Shape const * const me);
static void Shape_draw_(Shape const * const me);
// 構(gòu)造函數(shù)
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 類的虛函數(shù)實(shí)現(xiàn)
static uint32_t Shape_area_(Shape const * const me)
{
assert(0); // 類似純虛函數(shù)
return 0U; // 避免警告
}
static void Shape_draw_(Shape const * const me)
{
assert(0); // 純虛函數(shù)不能被調(diào)用
}
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 < nShapes; ++i)
{
uint32_t area = Shape_area(shapes[i]);// 虛函數(shù)調(diào)用
if (area > max)
{
max = area;
s = shapes[i];
}
}
return s;
}
void drawAllShapes(Shape const *shapes[], uint32_t nShapes)
{
uint32_t i;
for (i = 0U; i < nShapes; ++i)
{
Shape_draw(shapes[i]); // 虛函數(shù)調(diào)用
}
}
注釋比較清晰,這里不再多做解釋。
4.3 繼承 vtbl 和 重載 vptr
上面已經(jīng)提到過,基類包含 vptr,子類會自動(dòng)繼承。但是,vptr 需要被子類的虛表重新賦值。并且,這也必須發(fā)生在子類的構(gòu)造函數(shù)中。下面是 Rectangle 的構(gòu)造函數(shù)。
#include "rect.h"
#include <stdio.h>
// Rectangle 虛函數(shù)
static uint32_t Rectangle_area_(Shape const * const me);
static void Rectangle_draw_(Shape const * const me);
// 構(gòu)造函數(shù)
void Rectangle_ctor(Rectangle * const me, int16_t x, int16_t y,
uint16_t width, uint16_t height)
{
static struct ShapeVtbl const vtbl =
{
&Rectangle_area_,
&Rectangle_draw_
};
Shape_ctor(&me->super, x, y); // 調(diào)用基類的構(gòu)造函數(shù)
me->super.vptr = &vtbl; // 重載 vptr
me->width = width;
me->height = height;
}
// Rectangle's 虛函數(shù)實(shí)現(xiàn)
static uint32_t Rectangle_area_(Shape const * const me)
{
Rectangle const * const me_ = (Rectangle const *)me; //顯示的轉(zhuǎn)換
return (uint32_t)me_->width * (uint32_t)me_->height;
}
static void Rectangle_draw_(Shape const * const me)
{
Rectangle const * const me_ = (Rectangle const *)me; //顯示的轉(zhuǎn)換
printf("Rectangle_draw_(x=%d,y=%d,width=%d,height=%d)\n",
Shape_getX(me), Shape_getY(me), me_->width, me_->height);
}
4.4 虛函數(shù)調(diào)用
有了前面虛表(Virtual Tables)和虛指針(Virtual Pointers)的基礎(chǔ)實(shí)現(xiàn),虛擬調(diào)用(后期綁定)就可以用下面代碼實(shí)現(xiàn)了。
uint32_t Shape_area(Shape const * const me)
{
return (*me->vptr->area)(me);
}
這個(gè)函數(shù)可以放到.c文件里面,但是會帶來一個(gè)缺點(diǎn)就是每個(gè)虛擬調(diào)用都有額外的調(diào)用開銷。為了避免這個(gè)缺點(diǎn),如果編譯器支持內(nèi)聯(lián)函數(shù)(C99)。我們可以把定義放到頭文件里面,類似下面:
static inline uint32_t Shape_area(Shape const * const me)
{
return (*me->vptr->area)(me);
}
如果是老一點(diǎn)的編譯器(C89),我們可以用宏函數(shù)來實(shí)現(xiàn),類似下面這樣:
#define Shape_area(me_) ((*(me_)->vptr->area)((me_)))
看一下例子中的調(diào)用機(jī)制:

4.5 main.c
#include "rect.h"
#include "circle.h"
#include <stdio.h>
int main()
{
Rectangle r1, r2;
Circle c1, c2;
Shape const *shapes[] =
{
&c1.super,
&r2.super,
&c2.super,
&r1.super
};
Shape const *s;
// 實(shí)例化矩形對象
Rectangle_ctor(&r1, 0, 2, 10, 15);
Rectangle_ctor(&r2, -1, 3, 5, 8);
// 實(shí)例化圓形對象
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)\n", Shape_getX(s), Shape_getY(s));
drawAllShapes(shapes, sizeof(shapes)/sizeof(shapes[0]));
return 0;
}
輸出結(jié)果:
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)
5、總結(jié)
還是那句話,面向?qū)ο缶幊淌且环N方法,并不局限于某一種編程語言。用 C 語言實(shí)現(xiàn)封裝、單繼承,理解和實(shí)現(xiàn)起來比較簡單,多態(tài)反而會稍微復(fù)雜一點(diǎn),如果打算廣泛的使用多態(tài),還是推薦轉(zhuǎn)到 C++ 語言上,畢竟這層復(fù)雜性被這個(gè)語言給封裝了,你只需要簡單的使用就行了。但并不代表,C 語言實(shí)現(xiàn)不了多態(tài)這個(gè)特性。
以上就是C語言實(shí)現(xiàn)面向?qū)ο蟮姆椒ㄔ斀獾脑敿?xì)內(nèi)容,更多關(guān)于C語言實(shí)現(xiàn)面向?qū)ο蟮馁Y料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
-
C++中字符串全排列算法及next_permutation原理詳解
這篇文章主要為大家詳細(xì)介紹了C++中字符串全排列(遞歸法)和(迭代法)以及next_permutation底層原理,文中的示例代碼講解詳細(xì),感興趣的可以了解一下 2023-02-02
-
關(guān)于嘗試開發(fā)PHP的MYSQL擴(kuò)展的使用
本篇文章小編將為大家介紹,關(guān)于嘗試開發(fā)PHP的MYSQL擴(kuò)展的使用,需要的朋友可以參考一下 2013-04-04
-
Visual Studio Code 從簡介、安裝到配置所需插件詳細(xì)介紹
這篇文章給大家介紹到vs與vs code的區(qū)別,并且會詳細(xì)介紹vscode的安裝步驟,和我所了解過的插件配置,感興趣的朋友跟隨小編一起看看吧 2020-03-03
-
C語言二叉樹常見操作詳解【前序,中序,后序,層次遍歷及非遞歸查找,統(tǒng)計(jì)個(gè)數(shù),比較,求深度】
這篇文章主要介紹了C語言二叉樹常見操作,結(jié)合實(shí)例形式詳細(xì)分析了基于C語言的二叉樹前序,中序,后序,層次遍歷及非遞歸查找,統(tǒng)計(jì)個(gè)數(shù),比較,求深度等相關(guān)操作技巧與注意事項(xiàng),需要的朋友可以參考下 2018-04-04
-
C++ Boost PropertyTree示例超詳細(xì)講解
Boost是為C++語言標(biāo)準(zhǔn)庫提供擴(kuò)展的一些C++程序庫的總稱。Boost庫是一個(gè)可移植、提供源代碼的C++庫,作為標(biāo)準(zhǔn)庫的后備,是C++標(biāo)準(zhǔn)化進(jìn)程的開發(fā)引擎之一,是為C++語言標(biāo)準(zhǔn)庫提供擴(kuò)展的一些C++程序庫的總稱
2022-11-11
-
數(shù)據(jù)結(jié)構(gòu)課程設(shè)計(jì)- 解析最少換車次數(shù)的問題詳解
數(shù)據(jù)結(jié)構(gòu)課程設(shè)計(jì)- 解析最少換車次數(shù)的問題詳解 2013-05-05
最新評論
1、引言
面向?qū)ο缶幊蹋∣OP)并不是一種特定的語言或者工具,它只是一種設(shè)計(jì)方法、設(shè)計(jì)思想。它表現(xiàn)出來的三個(gè)最基本的特性就是封裝、繼承與多態(tài)。很多面向?qū)ο蟮木幊陶Z言已經(jīng)包含這三個(gè)特性了,例如 Smalltalk、C++、Java。但是你也可以用幾乎所有的編程語言來實(shí)現(xiàn)面向?qū)ο缶幊?,例?ANSI-C。要記住,面向?qū)ο笫且环N思想,一種方法,不要太拘泥于編程語言。
2、封裝
封裝就是把數(shù)據(jù)和方法打包到一個(gè)類里面。其實(shí)C語言編程者應(yīng)該都已經(jīng)接觸過了,C 標(biāo)準(zhǔn)庫中的 fopen(), fclose(), fread(), fwrite()等函數(shù)的操作對象就是 FILE。數(shù)據(jù)內(nèi)容就是 FILE,數(shù)據(jù)的讀寫操作就是 fread()、fwrite(),fopen() 類比于構(gòu)造函數(shù),fclose() 就是析構(gòu)函數(shù)。這個(gè)看起來似乎很好理解,那下面我們實(shí)現(xiàn)一下基本的封裝特性。
#ifndef SHAPE_H #define SHAPE_H #include <stdint.h> // Shape 的屬性 typedef struct { int16_t x; int16_t y; } Shape; // Shape 的操作函數(shù),接口函數(shù) 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 類相關(guān)的定義,當(dāng)然是在 “Shape.c” 里面。
#include "shape.h" // 構(gòu)造函數(shù) 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; } // 獲取屬性值函數(shù) 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 <stdio.h> /* 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)\n", Shape_getX(&s1), Shape_getY(&s1)); printf("Shape s2(x=%d,y=%d)\n", Shape_getX(&s2), Shape_getY(&s2)); Shape_moveBy(&s1, 2, -4); Shape_moveBy(&s2, 1, -2); printf("Shape s1(x=%d,y=%d)\n", Shape_getX(&s1), Shape_getY(&s1)); printf("Shape s2(x=%d,y=%d)\n", Shape_getX(&s2), Shape_getY(&s2)); return 0; }
編譯之后,看看執(zhí)行結(jié)果:
Shape s1(x=0,y=1)
Shape s2(x=-1,y=2)
Shape s1(x=2,y=-3)
Shape s2(x=0,y=0)
整個(gè)例子,非常簡單,非常好理解。以后寫代碼時(shí)候,要多去想想標(biāo)準(zhǔn)庫的文件IO操作,這樣也有意識的去培養(yǎng)面向?qū)ο缶幊痰乃季S。
3、繼承
繼承就是基于現(xiàn)有的一個(gè)類去定義一個(gè)新類,這樣有助于重用代碼,更好的組織代碼。在 C 語言里面,去實(shí)現(xiàn)單繼承也非常簡單,只要把基類放到繼承類的第一個(gè)數(shù)據(jù)成員的位置就行了。
例如,我們現(xiàn)在要?jiǎng)?chuàng)建一個(gè) Rectangle 類,我們只要繼承 Shape 類已經(jīng)存在的屬性和操作,再添加不同于 Shape 的屬性和操作到 Rectangle 中。
下面是 Rectangle 的聲明與定義:
#ifndef RECT_H #define RECT_H #include "shape.h" // 基類接口 // 矩形的屬性 typedef struct { Shape super; // 繼承 Shape // 自己的屬性 uint16_t width; uint16_t height; } Rectangle; // 構(gòu)造函數(shù) void Rectangle_ctor(Rectangle * const me, int16_t x, int16_t y, uint16_t width, uint16_t height); #endif /* RECT_H */
#include "rect.h" // 構(gòu)造函數(shù) 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 的繼承關(guān)系和內(nèi)存布局
因?yàn)橛羞@樣的內(nèi)存布局,所以你可以很安全的傳一個(gè)指向 Rectangle 對象的指針到一個(gè)期望傳入 Shape 對象的指針的函數(shù)中,就是一個(gè)函數(shù)的參數(shù)是 “Shape *”,你可以傳入 “Rectangle *”,并且這是非常安全的。這樣的話,基類的所有屬性和方法都可以被繼承類繼承!
#include "rect.h" #include <stdio.h> int main() { Rectangle r1, r2; // 實(shí)例化對象 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)\n", Shape_getX(&r1.super), Shape_getY(&r1.super), r1.width, r1.height); printf("Rect r2(x=%d,y=%d,width=%d,height=%d)\n", Shape_getX(&r2.super), Shape_getY(&r2.super), r2.width, r2.height); // 注意,這里有兩種方式,一是強(qiáng)轉(zhuǎn)類型,二是直接使用成員地址 Shape_moveBy((Shape *)&r1, -2, 3); Shape_moveBy(&r2.super, 2, -1); printf("Rect r1(x=%d,y=%d,width=%d,height=%d)\n", Shape_getX(&r1.super), Shape_getY(&r1.super), r1.width, r1.height); printf("Rect r2(x=%d,y=%d,width=%d,height=%d)\n", Shape_getX(&r2.super), Shape_getY(&r2.super), r2.width, r2.height); return 0; }
輸出結(jié)果:
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)
4、多態(tài)
C++ 語言實(shí)現(xiàn)多態(tài)就是使用虛函數(shù)。在 C 語言里面,也可以實(shí)現(xiàn)多態(tài)。
現(xiàn)在,我們又要增加一個(gè)圓形,并且在 Shape 要擴(kuò)展功能,我們要增加 area() 和 draw() 函數(shù)。但是 Shape 相當(dāng)于抽象類,不知道怎么去計(jì)算自己的面積,更不知道怎么去畫出來自己。而且,矩形和圓形的面積計(jì)算方式和幾何圖像也是不一樣的。
下面讓我們重新聲明一下 Shape 類
#ifndef SHAPE_H #define SHAPE_H #include <stdint.h> 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 的操作函數(shù),接口函數(shù) 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 */
看下加上虛函數(shù)之后的類關(guān)系圖
4.1 虛表和虛指針
虛表(Virtual Table)是這個(gè)類所有虛函數(shù)的函數(shù)指針的集合。
虛指針(Virtual Pointer)是一個(gè)指向虛表的指針。這個(gè)虛指針必須存在于每個(gè)對象實(shí)例中,會被所有子類繼承。
在《Inside The C++ Object Model》的第一章內(nèi)容中,有這些介紹。
4.2 在構(gòu)造函數(shù)中設(shè)置vptr
在每一個(gè)對象實(shí)例中,vptr 必須被初始化指向其 vtbl。最好的初始化位置就是在類的構(gòu)造函數(shù)中。事實(shí)上,在構(gòu)造函數(shù)中,C++ 編譯器隱式的創(chuàng)建了一個(gè)初始化的vptr。在 C 語言里面, 我們必須顯示的初始化vptr。
下面就展示一下,在 Shape 的構(gòu)造函數(shù)里面,如何去初始化這個(gè) vptr。
#include "shape.h" #include <assert.h> // Shape 的虛函數(shù) static uint32_t Shape_area_(Shape const * const me); static void Shape_draw_(Shape const * const me); // 構(gòu)造函數(shù) 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 類的虛函數(shù)實(shí)現(xiàn) static uint32_t Shape_area_(Shape const * const me) { assert(0); // 類似純虛函數(shù) return 0U; // 避免警告 } static void Shape_draw_(Shape const * const me) { assert(0); // 純虛函數(shù)不能被調(diào)用 } 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 < nShapes; ++i) { uint32_t area = Shape_area(shapes[i]);// 虛函數(shù)調(diào)用 if (area > max) { max = area; s = shapes[i]; } } return s; } void drawAllShapes(Shape const *shapes[], uint32_t nShapes) { uint32_t i; for (i = 0U; i < nShapes; ++i) { Shape_draw(shapes[i]); // 虛函數(shù)調(diào)用 } }
注釋比較清晰,這里不再多做解釋。
4.3 繼承 vtbl 和 重載 vptr
上面已經(jīng)提到過,基類包含 vptr,子類會自動(dòng)繼承。但是,vptr 需要被子類的虛表重新賦值。并且,這也必須發(fā)生在子類的構(gòu)造函數(shù)中。下面是 Rectangle 的構(gòu)造函數(shù)。
#include "rect.h" #include <stdio.h> // Rectangle 虛函數(shù) static uint32_t Rectangle_area_(Shape const * const me); static void Rectangle_draw_(Shape const * const me); // 構(gòu)造函數(shù) void Rectangle_ctor(Rectangle * const me, int16_t x, int16_t y, uint16_t width, uint16_t height) { static struct ShapeVtbl const vtbl = { &Rectangle_area_, &Rectangle_draw_ }; Shape_ctor(&me->super, x, y); // 調(diào)用基類的構(gòu)造函數(shù) me->super.vptr = &vtbl; // 重載 vptr me->width = width; me->height = height; } // Rectangle's 虛函數(shù)實(shí)現(xiàn) static uint32_t Rectangle_area_(Shape const * const me) { Rectangle const * const me_ = (Rectangle const *)me; //顯示的轉(zhuǎn)換 return (uint32_t)me_->width * (uint32_t)me_->height; } static void Rectangle_draw_(Shape const * const me) { Rectangle const * const me_ = (Rectangle const *)me; //顯示的轉(zhuǎn)換 printf("Rectangle_draw_(x=%d,y=%d,width=%d,height=%d)\n", Shape_getX(me), Shape_getY(me), me_->width, me_->height); }
4.4 虛函數(shù)調(diào)用
有了前面虛表(Virtual Tables)和虛指針(Virtual Pointers)的基礎(chǔ)實(shí)現(xiàn),虛擬調(diào)用(后期綁定)就可以用下面代碼實(shí)現(xiàn)了。
uint32_t Shape_area(Shape const * const me) { return (*me->vptr->area)(me); }
這個(gè)函數(shù)可以放到.c文件里面,但是會帶來一個(gè)缺點(diǎn)就是每個(gè)虛擬調(diào)用都有額外的調(diào)用開銷。為了避免這個(gè)缺點(diǎn),如果編譯器支持內(nèi)聯(lián)函數(shù)(C99)。我們可以把定義放到頭文件里面,類似下面:
static inline uint32_t Shape_area(Shape const * const me) { return (*me->vptr->area)(me); }
如果是老一點(diǎn)的編譯器(C89),我們可以用宏函數(shù)來實(shí)現(xiàn),類似下面這樣:
#define Shape_area(me_) ((*(me_)->vptr->area)((me_)))
看一下例子中的調(diào)用機(jī)制:
4.5 main.c
#include "rect.h" #include "circle.h" #include <stdio.h> int main() { Rectangle r1, r2; Circle c1, c2; Shape const *shapes[] = { &c1.super, &r2.super, &c2.super, &r1.super }; Shape const *s; // 實(shí)例化矩形對象 Rectangle_ctor(&r1, 0, 2, 10, 15); Rectangle_ctor(&r2, -1, 3, 5, 8); // 實(shí)例化圓形對象 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)\n", Shape_getX(s), Shape_getY(s)); drawAllShapes(shapes, sizeof(shapes)/sizeof(shapes[0])); return 0; }
輸出結(jié)果:
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)
5、總結(jié)
還是那句話,面向?qū)ο缶幊淌且环N方法,并不局限于某一種編程語言。用 C 語言實(shí)現(xiàn)封裝、單繼承,理解和實(shí)現(xiàn)起來比較簡單,多態(tài)反而會稍微復(fù)雜一點(diǎn),如果打算廣泛的使用多態(tài),還是推薦轉(zhuǎn)到 C++ 語言上,畢竟這層復(fù)雜性被這個(gè)語言給封裝了,你只需要簡單的使用就行了。但并不代表,C 語言實(shí)現(xiàn)不了多態(tài)這個(gè)特性。
以上就是C語言實(shí)現(xiàn)面向?qū)ο蟮姆椒ㄔ斀獾脑敿?xì)內(nèi)容,更多關(guān)于C語言實(shí)現(xiàn)面向?qū)ο蟮馁Y料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C++中字符串全排列算法及next_permutation原理詳解
這篇文章主要為大家詳細(xì)介紹了C++中字符串全排列(遞歸法)和(迭代法)以及next_permutation底層原理,文中的示例代碼講解詳細(xì),感興趣的可以了解一下2023-02-02關(guān)于嘗試開發(fā)PHP的MYSQL擴(kuò)展的使用
本篇文章小編將為大家介紹,關(guān)于嘗試開發(fā)PHP的MYSQL擴(kuò)展的使用,需要的朋友可以參考一下2013-04-04Visual Studio Code 從簡介、安裝到配置所需插件詳細(xì)介紹
這篇文章給大家介紹到vs與vs code的區(qū)別,并且會詳細(xì)介紹vscode的安裝步驟,和我所了解過的插件配置,感興趣的朋友跟隨小編一起看看吧2020-03-03C語言二叉樹常見操作詳解【前序,中序,后序,層次遍歷及非遞歸查找,統(tǒng)計(jì)個(gè)數(shù),比較,求深度】
這篇文章主要介紹了C語言二叉樹常見操作,結(jié)合實(shí)例形式詳細(xì)分析了基于C語言的二叉樹前序,中序,后序,層次遍歷及非遞歸查找,統(tǒng)計(jì)個(gè)數(shù),比較,求深度等相關(guān)操作技巧與注意事項(xiàng),需要的朋友可以參考下2018-04-04C++ Boost PropertyTree示例超詳細(xì)講解
Boost是為C++語言標(biāo)準(zhǔn)庫提供擴(kuò)展的一些C++程序庫的總稱。Boost庫是一個(gè)可移植、提供源代碼的C++庫,作為標(biāo)準(zhǔn)庫的后備,是C++標(biāo)準(zhǔn)化進(jìn)程的開發(fā)引擎之一,是為C++語言標(biāo)準(zhǔn)庫提供擴(kuò)展的一些C++程序庫的總稱2022-11-11數(shù)據(jù)結(jié)構(gòu)課程設(shè)計(jì)- 解析最少換車次數(shù)的問題詳解
數(shù)據(jù)結(jié)構(gòu)課程設(shè)計(jì)- 解析最少換車次數(shù)的問題詳解2013-05-05