如何在纯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;
}

备注

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

相关推荐
FuckPatience1 小时前
Visual Studio C# 项目中文件后缀简介
开发语言·c#
014-code8 小时前
订单超时取消与库存回滚的完整实现(延迟任务 + 状态机)
java·开发语言
lly2024068 小时前
组合模式(Composite Pattern)
开发语言
游乐码8 小时前
c#泛型约束
开发语言·c#
Dontla9 小时前
go语言Windows安装教程(安装go安装Golang安装)(GOPATH、Go Modules)
开发语言·windows·golang
chushiyunen9 小时前
python rest请求、requests
开发语言·python
铁东博客9 小时前
Go实现周易大衍筮法三变取爻
开发语言·后端·golang
baidu_huihui9 小时前
在 CentOS 9 上安装 pip(Python 的包管理工具)
开发语言·python·pip
南 阳9 小时前
Python从入门到精通day63
开发语言·python
lbb 小魔仙9 小时前
Python_RAG知识库问答系统实战指南
开发语言·python