【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;
}
相关推荐
鬼手点金13 小时前
Scrapy + Playwright 完整示例(JS 动态渲染网页)
开发语言·javascript·爬虫·python·scrapy·html·json
Mr. zhihao13 小时前
深度解析:为什么Java序列化需要搭配ByteArrayOutputStream?IO装饰器模式的精妙设计
java·开发语言·装饰器模式
格林威14 小时前
多相机并行采图最佳实践:Task.WhenAll + 异常处理 + 资源释放
开发语言·人工智能·数码相机·计算机视觉·c#·视觉检测·机器视觉
djjjx.14 小时前
【 C++ 】多态
开发语言·c++·多态
夜雪一千14 小时前
Python如何使用XPath定位没有特征的元素?无id、无class通用定位技巧
开发语言·python
艾莉丝努力练剑14 小时前
【QT:解决问题】Qt5Core.dll:无法定位程序输入点
java·开发语言·qt·学习·面试
流浪00114 小时前
Python 基础语法(一):常量、变量、输入输出与运算符
开发语言·python
光影少年14 小时前
react离线缓存、图片缓存方案
开发语言·前端·javascript·react native·react.js·缓存·前端框架
SomeB1oody14 小时前
【RustyML入门】3.7. 循环层
开发语言·后端·机器学习·rust·教程
言乐617 小时前
Python游戏水平测试辅助系统
开发语言·python·游戏·django·pygame