<分区>
我正在尝试将一些 C++ 代码转换为 C,但我遇到了一些问题。 如何在结构中定义函数?
像这样:
typedef struct {
double x, y, z;
struct Point *next;
struct Point *prev;
void act() {sth. to do here};
} Point;
<分区>
我正在尝试将一些 C++ 代码转换为 C,但我遇到了一些问题。 如何在结构中定义函数?
像这样:
typedef struct {
double x, y, z;
struct Point *next;
struct Point *prev;
void act() {sth. to do here};
} Point;
最佳答案
不,您不能在 C 中的 struct
中定义函数。
你可以在 struct
中有一个函数指针,但是有一个函数指针与 C++ 中的成员函数有很大不同,即没有隐式的 this
指针指向包含的 struct
实例。
人为的例子(在线演示 http://ideone.com/kyHlQ ):
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct point
{
int x;
int y;
void (*print)(const struct point*);
};
void print_x(const struct point* p)
{
printf("x=%d\n", p->x);
}
void print_y(const struct point* p)
{
printf("y=%d\n", p->y);
}
int main(void)
{
struct point p1 = { 2, 4, print_x };
struct point p2 = { 7, 1, print_y };
p1.print(&p1);
p2.print(&p2);
return 0;
}
关于我可以在 C 结构中定义函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12642830/