You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在C语言中能否实现C++类式的函数指针传递与调用功能?

能实现,C语言可通过结构体+函数指针模拟该功能

C语言没有C的类机制,但可以用结构体封装数据+函数指针的组合,完全模拟你描述的C功能。核心思路是用结构体替代类,用typedef替代C++的using定义函数指针类型,再通过普通函数模拟类的成员方法来调用函数指针。

实现步骤与示例代码

1. 定义函数指针类型(替代C++的using)

C语言用typedef定义函数指针类型,作用和C++的using一致,让代码更易读:

#include <stdio.h>
#include <assert.h>

// 先定义依赖的结构体(对应C++里的Surface、Vec2、RectI)
typedef struct {
    int x, y;
} Vec2;

typedef struct {
    int left, top, right, bottom;
} RectI;

// 定义函数指针类型,对应C++里的FunctionPtr
typedef void (*DrawFuncPtr)(int x, int y, const RectI* frame);

2. 用结构体模拟C++的Animation类

结构体里存储函数指针和其他成员变量:

typedef struct Animation {
    DrawFuncPtr DrawPointer; // 存储外部函数的指针
    int iCurrentFrame;       // 模拟类的成员变量
    RectI* frames;           // 帧数据
} Animation;

3. 编写模拟类成员函数的普通函数

C语言没有成员函数,所以写普通函数时,把结构体指针作为第一个参数(对应C++的this指针):

// 模拟Animation::Draw成员函数
void Animation_Draw(const Animation* anim, const Vec2* pos) {
    RectI temp = anim->frames[anim->iCurrentFrame];

    // 检查函数指针是否有效
    assert(anim->DrawPointer != NULL && "no pointer for drawing");
    
    if (anim->DrawPointer != NULL) {
        // 调用main上方的外部函数
        anim->DrawPointer(pos->x, pos->y, &temp);
    } else {
        fprintf(stderr, "no pointer for drawing.\n");
    }
}

4. 定义main函数上方的目标函数

这个函数的签名要和DrawFuncPtr完全匹配:

// main上方的外部函数,供Animation调用
void ExternalDraw(int x, int y, const RectI* frame) {
    printf("Drawing at (%d,%d), frame area: [%d,%d] to [%d,%d]\n",
           x, y, frame->left, frame->top, frame->right, frame->bottom);
}

5. 在main中使用

把外部函数指针赋值给结构体成员,然后调用模拟的成员函数:

int main() {
    // 初始化Animation实例
    Animation anim;
    anim.iCurrentFrame = 0;
    RectI frames[] = {{0, 0, 100, 100}, {100, 0, 200, 100}};
    anim.frames = frames;
    // 将main上方的函数指针赋值给结构体成员
    anim.DrawPointer = ExternalDraw;

    // 调用模拟的Draw方法
    Vec2 pos = {50, 50};
    Animation_Draw(&anim, &pos);

    return 0;
}

关键差异说明

  • C语言没有引用,所以参数中的引用类型要替换为指针(比如C++的const Surface&对应C的const Surface*)。
  • 用结构体+普通函数模拟类的封装,结构体指针替代this指针。
  • 用typedef替代C++的using定义函数指针类型,功能等价。

内容的提问来源于stack exchange,提问作者NaturalDemon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 14:10:39