【C语言】用 C 语言实现多态

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;
}
相关推荐
晓蛋3 天前
c语言指的是什么意思
c语言·编译器·编程开发·集成开发环境·程序实例
小羊没烦恼!3 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
傲世仙尊3 天前
目录即文件-Ext文件系统收尾篇
linux·c语言
牵猫散步的鱼儿3 天前
重载、重写(覆盖)、重定义区别
c语言
伞伞悦读3 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
phltxy3 天前
C 语言指针:从内存地址到灵活的数据访问
c语言
C语言小火车3 天前
C/C++ 为什么需要编译器?
开发语言·c++
phltxy3 天前
C 语言中的数据存储:从类型到二进制位
c语言
霍霍的袁3 天前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio
孙启超3 天前
【AI开发之Rust】第 11 课:智能指针与内部可变性
开发语言·后端·rust