用C語(yǔ)言實(shí)現(xiàn)C++ 繼承多態(tài)
#include <stdio.h>
#include <stdlib.h>
// 基類結(jié)構(gòu)體
typedef struct Base
{
void (*speak)(struct Base *); // 虛函數(shù)
} Base;
// 派生類結(jié)構(gòu)體
typedef struct Derived
{
Base base; // 基類子對(duì)象
int data;
} Derived;
// 基類虛函數(shù)的實(shí)現(xiàn)
void base_speak(Base *base)
{
printf("Base::speak\n");
}
// 派生類重寫虛函數(shù)的實(shí)現(xiàn)
void derived_speak(Base *base)
{
printf("Derived::speak\n");
Derived* derived = (Derived*)base;
printf("Derived::speak data=%d \n", derived->data);
}
// 初始化基類對(duì)象
void init_base(Base *base)
{
base->speak = base_speak; // 設(shè)置虛函數(shù)指針
}
// 初始化派生類對(duì)象
void init_derived(Derived *derived)
{
init_base((Base *)derived); // 調(diào)用基類初始化函數(shù)
derived->base.speak = derived_speak; // 重寫虛函數(shù)指針
derived->data = 42; // 設(shè)置派生類數(shù)據(jù)成員
}
int main()
{
Base *basePtr; // 基類指針
Derived derived; // 派生類對(duì)象
init_derived(&derived); // 初始化派生類對(duì)象
basePtr = (Base *)&derived; // 將基類指針指向派生類對(duì)象
basePtr->speak(basePtr); // 調(diào)用虛函數(shù)演熟,輸出 "Derived::speak"
return 0;
}