<dfn id="yhprb"><s id="yhprb"></s></dfn><dfn id="yhprb"><delect id="yhprb"></delect></dfn><dfn id="yhprb"></dfn><dfn id="yhprb"><delect id="yhprb"></delect></dfn><dfn id="yhprb"></dfn><dfn id="yhprb"><s id="yhprb"><strike id="yhprb"></strike></s></dfn><small id="yhprb"></small><dfn id="yhprb"></dfn><small id="yhprb"><delect id="yhprb"></delect></small><small id="yhprb"></small><small id="yhprb"></small> <delect id="yhprb"><strike id="yhprb"></strike></delect><dfn id="yhprb"></dfn><dfn id="yhprb"></dfn><s id="yhprb"><noframes id="yhprb"><small id="yhprb"><dfn id="yhprb"></dfn></small><dfn id="yhprb"><delect id="yhprb"></delect></dfn><small id="yhprb"></small><dfn id="yhprb"><delect id="yhprb"></delect></dfn><dfn id="yhprb"><s id="yhprb"></s></dfn> <small id="yhprb"></small><delect id="yhprb"><strike id="yhprb"></strike></delect><dfn id="yhprb"><s id="yhprb"></s></dfn><dfn id="yhprb"></dfn><dfn id="yhprb"><s id="yhprb"></s></dfn><dfn id="yhprb"><s id="yhprb"><strike id="yhprb"></strike></s></dfn><dfn id="yhprb"><s id="yhprb"></s></dfn>
"); //-->

博客專(zhuān)欄

EEPW首頁(yè) > 博客 > C語(yǔ)言的高級用法,面向對象

C語(yǔ)言的高級用法,面向對象

發(fā)布人:xiaomaidashu 時(shí)間:2022-06-22 來(lái)源:工程師 發(fā)布文章

不知道有多少人去了解過(guò)語(yǔ)言的發(fā)展史,早期C語(yǔ)言的語(yǔ)法功能其實(shí)比較簡(jiǎn)單。隨著(zhù)應用需求和場(chǎng)景的變化,C語(yǔ)言的語(yǔ)法功能在不斷升級變化。


雖然我們的教材有這么一個(gè)結論:C語(yǔ)言是面向過(guò)程的語(yǔ)言,C++是面向對象的編程語(yǔ)言,但面向對象的概念是在C語(yǔ)言階段就有了,而且應用到了很多地方,比如某些操作系統內核、通信協(xié)議等。


面向對象編程,也就是大家說(shuō)的OOP(Object Oriented Programming)并不是一種特定的語(yǔ)言或者工具,它只是一種設計方法、設計思想,它表現出來(lái)的三個(gè)最基本的特性就是封裝、繼承與多態(tài)。

1、為什么用C實(shí)現OOP   

閱讀文本之前肯定有讀者會(huì )問(wèn)這樣的問(wèn)題:我們有C++面向對象的語(yǔ)言,為什么還要用C語(yǔ)言實(shí)現面向對象呢?


C語(yǔ)言這種非面向對象的語(yǔ)言,同樣也可以使用面向對象的思路來(lái)編寫(xiě)程序的。

只是用面向對象的C++語(yǔ)言來(lái)實(shí)現面向對象編程會(huì )更簡(jiǎn)單一些,但是C語(yǔ)言的高效性是其他面向對象編程語(yǔ)言無(wú)法比擬的。


當然使用C語(yǔ)言來(lái)實(shí)現面向對象的開(kāi)發(fā)相對不容易理解,這就是為什么大多數人學(xué)過(guò)C語(yǔ)言卻看不懂Linux內核源碼。


所以這個(gè)問(wèn)題其實(shí)很好理解,只要有一定C語(yǔ)言編程經(jīng)驗的讀者都應該能明白:面向過(guò)程的C語(yǔ)言和面向對象的C++語(yǔ)言相比,代碼運行效率、代碼量都有很大差異。在性能不是很好、資源不是很多的MCU中使用C語(yǔ)言面向對象編程就顯得尤為重要。


2、所具備的條件   

要想使用C語(yǔ)言實(shí)現面向對象,首先需要具備一些基礎知識。比如:(C語(yǔ)言中的)結構體、函數、指針,以及函數指針等,(C++中的)基類(lèi)、派生、多態(tài)、繼承等。


首先,不僅僅是了解這些基礎知識,而是有一定的編程經(jīng)驗,因為上面說(shuō)了“面向對象是一種設計方法、設計思想”,如果只是停留在字面意思的理解,沒(méi)有這種設計思想肯定不行。


因此,不建議初學(xué)者使用C語(yǔ)言實(shí)現面向對象,特別是在真正項目中。建議把基本功練好,再使用。


利用C語(yǔ)言實(shí)現面向對象的方法很多,下面就來(lái)描述最基本的封裝、繼承和多態(tài)。

3、封裝  

封裝就是把數據和函數打包到一個(gè)類(lèi)里面,其實(shí)大部分C語(yǔ)言編程者都已近接觸過(guò)了。


C 標準庫中的 fopen(), fclose(), fread(), fwrite()等函數的操作對象就是 FILE。數據內容就是 FILE,數據的讀寫(xiě)操作就是 fread()、fwrite(),fopen() 類(lèi)比于構造函數,fclose() 就是析構函數。


這個(gè)看起來(lái)似乎很好理解,那下面我們實(shí)現一下基本的封裝特性。

#ifndef SHAPE_H
#define SHAPE_H
#include <stdint.h>
// 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 類(lèi)的聲明,非常簡(jiǎn)單,很好理解。一般會(huì )把聲明放到頭文件里面 “Shape.h”。來(lái)看下 Shape 類(lèi)相關(guān)的定義,當然是在 “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 <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;
}


編譯之后,看看執行結果:

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è)例子,非常簡(jiǎn)單,非常好理解。以后寫(xiě)代碼時(shí)候,要多去想想標準庫的文件IO操作,這樣也有意識的去培養面向對象編程的思維。

4、繼承  

繼承就是基于現有的一個(gè)類(lèi)去定義一個(gè)新類(lèi),這樣有助于重用代碼,更好的組織代碼。在 C 語(yǔ)言里面,去實(shí)現單繼承也非常簡(jiǎn)單,只要把基類(lèi)放到繼承類(lèi)的第一個(gè)數據成員的位置就行了。
例如,我們現在要創(chuàng )建一個(gè) Rectangle 類(lèi),我們只要繼承 Shape 類(lèi)已經(jīng)存在的屬性和操作,再添加不同于 Shape 的屬性和操作到 Rectangle 中。
下面是 Rectangle 的聲明與定義:

#ifndef RECT_H
#define RECT_H
#include "shape.h" // 基類(lèi)接口
// 矩形的屬性
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;
}


我們來(lái)看一下 Rectangle 的繼承關(guān)系和內存布局:


圖片


因為有這樣的內存布局,所以你可以很安全的傳一個(gè)指向 Rectangle 對象的指針到一個(gè)期望傳入 Shape 對象的指針的函數中,就是一個(gè)函數的參數是 “Shape *”,你可以傳入 “Rectangle *”,并且這是非常安全的。這樣的話(huà),基類(lèi)的所有屬性和方法都可以被繼承類(lèi)繼承!

#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);
    // 注意,這里有兩種方式,一是強轉類(lèi)型,二是直接使用成員地址
    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;
}

輸出結果:

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)
5、多態(tài)   

C++ 語(yǔ)言實(shí)現多態(tài)就是使用虛函數。在 C 語(yǔ)言里面,也可以實(shí)現多態(tài)。
現在,我們又要增加一個(gè)圓形,并且在 Shape 要擴展功能,我們要增加 area() 和 draw() 函數。但是 Shape 相當于抽象類(lèi),不知道怎么去計算自己的面積,更不知道怎么去畫(huà)出來(lái)自己。而且,矩形和圓形的面積計算方式和幾何圖像也是不一樣的。
下面讓我們重新聲明一下 Shape 類(lèi):

#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 的操作函數,接口函數
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 */

看下加上虛函數之后的類(lèi)關(guān)系圖:


圖片


5.1 虛表和虛指針

虛表(Virtual Table)是這個(gè)類(lèi)所有虛函數的函數指針的集合。


虛指針(Virtual Pointer)是一個(gè)指向虛表的指針。這個(gè)虛指針必須存在于每個(gè)對象實(shí)例中,會(huì )被所有子類(lèi)繼承。


在《Inside The C++ Object Model》的第一章內容中,有這些介紹。


5.2 在構造函數中設置vptr

在每一個(gè)對象實(shí)例中,vptr 必須被初始化指向其 vtbl。最好的初始化位置就是在類(lèi)的構造函數中。事實(shí)上,在構造函數中,C++ 編譯器隱式的創(chuàng )建了一個(gè)初始化的vptr。在 C 語(yǔ)言里面, 我們必須顯示的初始化vptr。


下面就展示一下,在 Shape 的構造函數里面,如何去初始化這個(gè) vptr。

#include "shape.h"
#include <assert.h>
// 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 類(lèi)的虛表
    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 類(lèi)的虛函數實(shí)現
static uint32_t Shape_area_(Shape const * const me) 
{
    assert(0); // 類(lèi)似純虛函數
    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 < nShapes; ++i) 
    {
        uint32_t area = Shape_area(shapes[i]);// 虛函數調用
        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]); // 虛函數調用
    }
}


5.3 繼承 vtbl 和 重載 vptr

上面已經(jīng)提到過(guò),基類(lèi)包含 vptr,子類(lèi)會(huì )自動(dòng)繼承。但是,vptr 需要被子類(lèi)的虛表重新賦值。并且,這也必須發(fā)生在子類(lèi)的構造函數中。下面是 Rectangle 的構造函數。

#include "rect.h"  
#include <stdio.h> 
// Rectangle 虛函數
static uint32_t Rectangle_area_(Shape const * const me);
static void Rectangle_draw_(Shape const * const me);
// 構造函數
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); // 調用基類(lèi)的構造函數
    me->super.vptr = &vtbl;           // 重載 vptr
    me->width = width;
    me->height = height;
}
// Rectangle's 虛函數實(shí)現
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)n",
           Shape_getX(me), Shape_getY(me), me_->width, me_->height);
}


5.4 虛函數調用

有了前面虛表(Virtual Tables)和虛指針(Virtual Pointers)的基礎實(shí)現,虛擬調用(后期綁定)就可以用下面代碼實(shí)現了。

uint32_t Shape_area(Shape const * const me)
{
    return (*me->vptr->area)(me);
}

這個(gè)函數可以放到.c文件里面,但是會(huì )帶來(lái)一個(gè)缺點(diǎn)就是每個(gè)虛擬調用都有額外的調用開(kāi)銷(xiāo)。為了避免這個(gè)缺點(diǎn),如果編譯器支持內聯(lián)函數(C99)。我們可以把定義放到頭文件里面,類(lèi)似下面:


static inline uint32_t Shape_area(Shape const * const me) 
{
    return (*me->vptr->area)(me);
}


如果是老一點(diǎn)的編譯器(C89),我們可以用宏函數來(lái)實(shí)現,類(lèi)似下面這樣:

#define Shape_area(me_) ((*(me_)->vptr->area)((me_)))


看一下例子中的調用機制:


圖片
5.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;
}

輸出結果:

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)
6、總結   

還是那句話(huà),面向對象編程是一種方法,并不局限于某一種編程語(yǔ)言。用 C 語(yǔ)言實(shí)現封裝、單繼承,理解和實(shí)現起來(lái)比較簡(jiǎn)單,多態(tài)反而會(huì )稍微復雜一點(diǎn),如果打算廣泛的使用多態(tài),還是推薦轉到 C++ 語(yǔ)言上,畢竟這層復雜性被這個(gè)語(yǔ)言給封裝了,你只需要簡(jiǎn)單的使用就行了。但并不代表,C 語(yǔ)言實(shí)現不了多態(tài)這個(gè)特性。

原文地址:https://blog.csdn.net/onlyshi/article/details/81672279

文章來(lái)源:嵌入式情報局,strongerhuang


*博客內容為網(wǎng)友個(gè)人發(fā)布,僅代表博主個(gè)人觀(guān)點(diǎn),如有侵權請聯(lián)系工作人員刪除。

linux操作系統文章專(zhuān)題:linux操作系統詳解(linux不再難懂)

linux相關(guān)文章:linux教程




關(guān)鍵詞: C語(yǔ)言

相關(guān)推薦

技術(shù)專(zhuān)區

關(guān)閉
国产精品自在自线亚洲|国产精品无圣光一区二区|国产日产欧洲无码视频|久久久一本精品99久久K精品66|欧美人与动牲交片免费播放
<dfn id="yhprb"><s id="yhprb"></s></dfn><dfn id="yhprb"><delect id="yhprb"></delect></dfn><dfn id="yhprb"></dfn><dfn id="yhprb"><delect id="yhprb"></delect></dfn><dfn id="yhprb"></dfn><dfn id="yhprb"><s id="yhprb"><strike id="yhprb"></strike></s></dfn><small id="yhprb"></small><dfn id="yhprb"></dfn><small id="yhprb"><delect id="yhprb"></delect></small><small id="yhprb"></small><small id="yhprb"></small> <delect id="yhprb"><strike id="yhprb"></strike></delect><dfn id="yhprb"></dfn><dfn id="yhprb"></dfn><s id="yhprb"><noframes id="yhprb"><small id="yhprb"><dfn id="yhprb"></dfn></small><dfn id="yhprb"><delect id="yhprb"></delect></dfn><small id="yhprb"></small><dfn id="yhprb"><delect id="yhprb"></delect></dfn><dfn id="yhprb"><s id="yhprb"></s></dfn> <small id="yhprb"></small><delect id="yhprb"><strike id="yhprb"></strike></delect><dfn id="yhprb"><s id="yhprb"></s></dfn><dfn id="yhprb"></dfn><dfn id="yhprb"><s id="yhprb"></s></dfn><dfn id="yhprb"><s id="yhprb"><strike id="yhprb"></strike></s></dfn><dfn id="yhprb"><s id="yhprb"></s></dfn>