【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;
}
相关推荐
不脱发的程序猿1 小时前
详解UDS CAN诊断:CommunicationControl Service(SID:0x28)
c语言·can·uds·汽车诊断·iso-tp
炸膛坦客3 小时前
单片机/C/C++八股:(三十七)指针数组 和 数组指针
c语言·开发语言·c++
夜不会漫长3 小时前
C++:C++11特性
开发语言·c++·算法
apcipot_rain4 小时前
C++转java日记(13)
java·开发语言
郝学胜-神的一滴5 小时前
Effective Python 条款41:试Mix‑In组合式开发
开发语言·pytorch·python·pycharm·numpy
吃我一窝jio5 小时前
Python与Redis集合深度解析
开发语言·redis·笔记·python
星恒随风6 小时前
从0实现C++ AI大模型接入SDK(五):DeepSeekProvider的实现——策略模式、HTTP请求与SSE流式响应
linux·开发语言·c++·人工智能
饮水桶_T7 小时前
Git笔记
开发语言·笔记·算法
国科安芯7 小时前
让每一瓦热都听话:航天器主动热控系统CANFD控制网络的可靠性设计
开发语言·网络·单片机·嵌入式硬件·信息与通信·抗辐射·载荷
CoderYanger7 小时前
Java EE 进阶:12.Spring AOP(第一弹)
java·开发语言·spring boot·后端·spring·java-ee·交互