我得承认.我缺乏使用C语言的经验,因此我不确定如何为 struct 实现函数.答案有很多:Define functions in structsCan I define a function inside a C structure?C - function inside struct,但它们没有回答我所寻找的结果.现在我想要的是:

假设我有一个这样的 struct :

typedef struct Ball {
  float x, y;
  float speedX, speedY;
  float radius;
  void (*Draw)();
} Ball;

现在,我希望DRAW函数能够访问Ball变量的成员,就像我在C++中有一个 struct 的实例一样.该函数应该能够访问变量并根据我的意愿对其进行修改.这有可能吗?

我试过一些像这样荒谬的事情,但没有任何结果.

typedef struct Ball {
  float x, y;
  float speedX, speedY;
  float radius;
  void (*Draw)();
} Ball;

void Draw(float *x, float *y, float *speedX, float *speedY, float *radius) {
  DrawCircle((int)*x, (int)*y, (int)*radius, WHITE);
}

这里是C++的类似功能:

    struct Ball {
        float x{}, y{};
        float speedX{}, speedY{};
        float radius{};
        void Draw() {
            DrawCircle((int)x, (int)y, (int)radius, WHITE); //I know I could static_cast, but who cares :)
        }
    };
int main(int argc, char ** argv) {
    Ball ball;
    ball.x = 100.f;
   ...
    ball.Draw();
}

正如你所看到的,C++方式非常简单,我就是搞不懂C.

推荐答案

只需按以下方式声明要执行函数的指针

typedef struct Ball {
  float x, y;
  float speedX, speedY;
  float radius;
  void (*Draw)( struct Ball * );
} Ball;

当函数被调用时,向其传递一个指向 struct 类型对象的指针.

例如

Ball ball = { /* initializers of data members of the structure */ };

ball.Draw( &ball );

该功能可以被实现,例如

void Draw( struct Ball *ball ) 
{
    DrawCircle( ball->x, ball->y, ball->radius, WHITE );
}

并且 struct 类型的对象的数据成员绘制可以被分配如下

ball.Draw = Draw;

或者,您可以像这样声明函数DrawCircle

void DrawCircle( struct Ball *ball );

只要它仅用于类型为struct Ball的对象.

并使用此函数直接初始化数据成员绘制

ball.Draw = DrawCircle;

C++相关问答推荐

如何在C中的空指针函数中传递浮点值

在x86汇编中,为什么当分子来自RDRAND时DIV会引发异常?

如何确保内存分配在地址附近?

如何启用ss(另一个调查套接字的实用程序)来查看Linux主机上加入的多播组IP地址?

C指针地址和转换

如果我释放其他内容,返回值就会出错

我可以在C中声明不同长度数组的数组而不带变量名吗?

Char变量如何在不使用方括号或花括号的情况下存储字符串,以及它如何迭代到下一个字符?

使用scanf在C中读取和存储文件中的值

如何在下面的C代码中正确管理内存?

tick.q中的Kdb+键控表语法

在for循环中指向数组开头之前

当内存来自Malloc时,将char*转换为另一个指针类型是否违反了严格的别名规则?

如果格式字符串的内存与printf的一个参数共享,会发生什么情况?

如何在不读取整个字符串的情况下删除UTF8字符串的尾随空格以提高性能?

为什么我的二叉树删除删除整个左部分的树?

无法将字符串文字分配给 C 中的字符数组

传递参数:C 和 C++ 中 array 与 *&array 和 &array[0] 的区别

在 C 中传递参数时出现整数溢出

(GNU+Linux) 多个线程同时调用malloc()