基本实现原理
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;
}
备注
个人水平有限,有问题随时交流~