我得承认.我缺乏使用C语言的经验,因此我不确定如何为 struct 实现函数.答案有很多:Define functions in structs、Can 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.