【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;
}
相关推荐
threelab8 小时前
Three.js 动态旋转同心圆着色器 | 三维可视化效果
开发语言·javascript·着色器
我不是懒洋洋8 小时前
手写一个B+树:从原理到数据库索引实战
c语言·c++·经验分享
奶茶树8 小时前
【STL/数据结构】哈希表和unordered系列容器的封装
开发语言·c++·散列表
Brilliantwxx8 小时前
【C++】初步认识STL(3)
开发语言·c++·笔记·算法
charlie1145141918 小时前
通用GUI编程技术——图形渲染实战(四十)——深度缓冲与3D变换:从平面到立体
开发语言·c++·平面·3d·图形渲染·win32
小张同学8248 小时前
-RAG检索增强生成让智能体拥有企业级专属知识库
开发语言·python·架构·pycharm
DevilSeagull8 小时前
Rust 枚举(enum)深度解析:从定义到 Option 的安全之道
开发语言·后端·安全·rust·github
Ulyanov9 小时前
《现代 Python 桌面应用架构实战:PySide6 + QML 从入门到工程化》:实时时钟与数据驱动 UI —— 从“事件回调”到“状态绑定”的范式跃迁
开发语言·python·qt·ui·架构·交互
AI进化营-智能译站9 小时前
ROS2 C++开发系列06:变量、数据类型与IO实战
java·开发语言·c++·ai