【发布时间】:2012-09-20 12:07:21
【问题描述】:
我正在尝试将一些 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;
}
【讨论】:
point* 是什么意思?我的意思是,在变量名后面加上 * 是什么意思?
point* p 表示将指向结构的指针作为参数传递。这样,就可以节省内存(作为值传递会在堆栈上创建变量的副本)。 point* 表示它是指向结构 p 的指针,而 point 表示它是一个结构,并将作为原始结构的副本传递。
你可以在结构中拥有一个函数指针。但不是这样
你可以这样定义
示例:
typedef struct cont_func
{
int var1;
int (*func)(int x, int y);
void *input;
} cont_func;
int max (int x, int y)
{
return (x > y) ? x : y;
}
int main () {
struct cont_func T;
T.func = max;
}
【讨论】:
在C 中,不允许在struct 中定义方法。您可以在结构中定义函数指针,如下所示:
typedef struct {
double x, y, z;
struct Point *next;
struct Point *prev;
void (*act)();
} Point;
每当您实例化 struct 时,您都必须将指针分配给特定函数。
【讨论】:
不,不可能在 C 中的结构内声明函数。
这是 C 和 C++ 之间的基本区别之一。
【讨论】:
这个想法是在结构中放置一个指向函数的指针。然后在结构之外声明该函数。这与 C++ 中在类中声明函数的类不同。
struct t {
int a;
void (*fun) (int * a);
} ;
void get_a (int * a) {
printf (" input : ");
scanf ("%d", a);
}
int main () {
struct t test;
test.a = 0;
printf ("a (before): %d\n", test.a);
test.fun = get_a;
test.fun(&test.a);
printf ("a (after ): %d\n", test.a);
return 0;
}
其中 test.fun = get_a; 将函数分配给结构中的指针,test.fun(&test.a); 调用它。
【讨论】:
您只能在不同于 C++ 的 C 编程语言的结构中定义函数指针。
【讨论】: