基本實現原理
/* 通過結構體+函數指針模擬類 */
typedef struct {// 成員變量int x; // 成員方法(函數指針) void (*print)(void* self);
} MyClass;/* 成員函數實現 */
void my_print(void* self) {MyClass* obj = (MyClass*)self;printf("Value: %d\n", obj->x);
}/* 構造函數 */
MyClass* MyClass_create(int x) {MyClass* obj = malloc(sizeof(MyClass));obj->x = x;obj->print = my_print; // 方法綁定return obj;
}
🔀 三種核心特性實現
1. 封裝
// 頭文件(.h)中只聲明結構體指針
typedef struct HiddenClass HiddenClass;// 源文件(.c)中定義真實結構體
struct HiddenClass {int private_data;void (*public_method)(HiddenClass*);
};
2. 繼承
/* 基類 */
typedef struct {int base_val;void (*base_method)();
} Base;/* 派生類 */
typedef struct {Base super; // 包含基類實現繼承int derived_val;
} Derived;
3. 多態
typedef struct {void (*speak)();
} Animal;void dog_speak() { printf("汪汪汪\n"); }
void cat_speak() { printf("喵喵喵\n"); }Animal dog = { .speak = dog_speak };
Animal cat = { .speak = cat_speak };
🧩 完整示例:圖形系統
/* 基類:Shape */
typedef struct Shape Shape;
struct Shape {void (*draw)(Shape*);
};/* 派生類:Circle */
typedef struct {Shape parent; // 繼承int radius;
} Circle;void circle_draw(Shape* self) {Circle* c = (Circle*)self;printf("繪制半徑%d的圓\n", c->radius);
}Circle* create_circle(int r) {Circle* c = malloc(sizeof(Circle));c->parent.draw = circle_draw;c->radius = r;return c;
}
備注
個人水平有限,有問題隨時交流~