C语言没有类的概念,但可以用结构体包含公共成员(类似基类),再通过函数指针实现动态绑定。
示例:图形面积计算
步骤1:定义"基类"Shape
cpp
// shape.h
#ifndef SHAPE_H
#define SHAPE_H
typedef struct Shape Shape;
// 函数指针类型定义
typedef double (*area_func_t)(const Shape*);
struct Shape {
area_func_t area; // 虚函数指针
};
// 统一调用接口(实现多态)
double shape_area(const Shape* shape);
#endif
步骤2:实现具体"派生类"
cpp
// circle.h
#ifndef CIRCLE_H
#define CIRCLE_H
#include "shape.h"
typedef struct {
Shape base; // 继承Shape
double radius;
} Circle;
void circle_init(Circle* circle, double radius);
#endif
cpp
// circle.c
#include "circle.h"
#include <math.h>
static double circle_area(const Shape* shape) {
const Circle* circle = (const Circle*)shape;
return M_PI * circle->radius * circle->radius;
}
void circle_init(Circle* circle, double radius) {
circle->base.area = circle_area; // 绑定具体实现
circle->radius = radius;
}
步骤3:实现统一调用接口
cpp
// shape.c
#include "shape.h"
double shape_area(const Shape* shape) {
if (shape && shape->area) {
return shape->area(shape);
}
return 0.0;
}
步骤4:使用多态
cpp
// main.c
#include <stdio.h>
#include "shape.h"
#include "circle.h"
// 还可定义 rectangle.h 等
int main() {
Circle c;
circle_init(&c, 5.0);
// 多态调用:通过基类指针调用实际类型的方法
Shape* shapes[] = { (Shape*)&c };
for (int i = 0; i < 1; ++i) {
printf("Area: %.2f\n", shape_area(shapes[i]));
}
return 0;
}