如何在纯C中实现类、继承和多态(小白友好版)

基本实现原理

c 复制代码
/* 通过结构体+函数指针模拟类 */
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. 封装

c 复制代码
// 头文件(.h)中只声明结构体指针
typedef struct HiddenClass HiddenClass;

// 源文件(.c)中定义真实结构体
struct HiddenClass {
    int private_data;
    void (*public_method)(HiddenClass*);
};

2. 继承

c 复制代码
/* 基类 */
typedef struct {
    int base_val;
    void (*base_method)();
} Base;

/* 派生类 */
typedef struct {
    Base super;  // 包含基类实现继承
    int derived_val;
} Derived;

3. 多态

c 复制代码
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 };

🧩 完整示例:图形系统

c 复制代码
/* 基类: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;
}

备注

个人水平有限,有问题随时交流~

相关推荐
祈安_2 天前
C语言内存函数
c语言·后端
郑州光合科技余经理4 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1234 天前
matlab画图工具
开发语言·matlab
dustcell.4 天前
haproxy七层代理
java·开发语言·前端
norlan_jame4 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone4 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054964 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
czy87874754 天前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
遥遥江上月4 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js
m0_531237174 天前
C语言-数组练习进阶
c语言·开发语言·算法