我们可以在C语言的结构中使用函数吗? 有人可以举例说明如何实施并解释一下吗?
答案 0 :(得分:4)
不,结构仅包含数据。但是,您可以在结构中定义指向函数的指针,如下所示:
struct myStruct {
int x;
void (*anotherFunction)(struct foo *);
}
答案 1 :(得分:0)
答案是否定的,但也有相同的效果。
只能在C程序的最外层找到函数。这通过减少与函数调用相关的内务管理来提高运行时速度。
因此,你不能在struct(或另一个函数内)中有一个函数,但在结构中有函数指针是很常见的。例如:
#include <stdio.h>
int get_int_global (void)
{
return 10;
}
double get_double_global (void)
{
return 3.14;
}
struct test {
int a;
double b;
};
struct test_func {
int (*get_int) (void);
double (*get_double)(void);
};
int main (void)
{
struct test_func t1 = {get_int_global, get_double_global};
struct test t2 = {10, 3.14};
printf("Using function pointers: %d, %f\n", t1.get_int(), t1.get_double());
printf("Using built-in types: %d, %f\n", t2.a, t2.b);
return 0;
}
很多人还会在结构中使用函数指针的命名约定,并会输入它们的函数指针。例如,您可以声明包含如下指针的结构:
typedef int (*get_int_fptr) (void);
typedef double (*get_double_fptr)(void);
struct test_func {
get_int_fptr get_int;
get_double_fptr get_double;
};
上面代码中的其他所有内容都可以正常工作。现在,get_int_fptr是一个返回int的函数的特殊类型,如果你假设* _fptr都是函数指针,那么只需查看typedef就可以找到函数签名。
答案 2 :(得分:-2)
不,它必须像这样实现:
typedef struct S_House {
char* name;
int opened;
} House;
void openHouse(House* theHouse);
void openHouse(House* theHouse) {
theHouse->opened = 1;
}
int main() {
House myHouse;
openHouse(&myHouse);
return 0;
}