首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> C 語言基礎

C 語言實現多態:函數指針構造虛表、橋接模式與對象池管理實戰

     編輯:C 語言基礎

背景:C++ 虛函數表機制

C++ 類含 virtual 函數時,編譯器生成 vptr(虛表指針) 指向 vtbl(虛函數表)。VC 中 Interface 宏實為 struct,揭示了本質:結構體封裝函數指針數組即可模擬純虛類。

C 語言純虛結構實現

typedef struct {
    void (*Foo1)();
    char (*Foo2)();
    char* (*Foo3)(char* st);
} MyVirtualInterface;

橋接模式落地

主類 DoMyAct 持有 MyVirtualInterface *m_pInterface:

void DoMyAct_SetInterface(MyVirtualInterface* p) { m_pInterface = p; }
void DoMyAct_Do() {
    if (!m_pInterface) return;
    m_pInterface->Foo1();
    char c = m_pInterface->Foo2();
}

子類 Act1 實現虛結構,管理對象池:

MyVirtualInterface st[MAX];
MyVirtualInterface* Act1_CreateInterface() {
    int index = FindValid();  // 對象池或 malloc
    if (index == -1) return NULL;
    st[index].Foo1 = Act1_Foo1;
    st[index].Foo2 = Act1_Foo2;
    st[index].Foo3 = Act1_Foo3;
    return &st[index];
}

Act2 同理。main 中統一管理:

List_AddObject(&List, Act1_CreateInterface());
while (p = List_GetObject()) {
    DoMyAct_SetInterface(p);
    DoMyAct_Do();  // 不關心具體實現,just do it
}

核心優勢

  • 消除大量 switch-case,實現開閉原則。
  • 對象池管理實例生命周期,避免頻繁 malloc/free。
  • 純 C 實現運行時多態,零 C++ 依賴,適合嵌入式/內核開發。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved