[英]Can there be functions inside structures?
Can we have functions in structures in C language? 我们可以使用C语言的结构函数吗?
Could someone please give an example of how to implement it and explain? 有人可以举例说明如何实施和解释吗?
No, structures contain data only. 不,结构仅包含数据。 However, you can define a pointer to a function inside of a struct as below:
但是,可以在结构内部定义指向函数的指针,如下所示:
struct myStruct {
int x;
void (*anotherFunction)(struct foo *);
}
The answer is no, but there is away to get the same effect. 答案是否定的,但是有可能获得相同的效果。
Functions can only be found at the outermost level of a C program. 函数只能在C程序的最外层找到。 This improves run-time speed by reducing the housekeeping associated with function calls.
通过减少与函数调用相关的内务处理,这提高了运行速度。
As such, you cannot have a function inside of a struct (or inside of another function) but it is very common to have function pointers inside structures . 这样,您不能在结构内部(或另一个函数内部)具有函数,但是在结构内部具有函数指针是很常见的。 For example:
例如:
#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;
}
A lot of people will also use a naming convention for function pointers inside structures and will typedef their function pointers. 很多人还将对结构内部的函数指针使用命名约定,并会对其函数指针进行类型定义。 For example you could declare the structure containing pointers like this:
例如,您可以声明包含如下指针的结构:
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;
};
Everything else in the code above will work as it is. 上面代码中的所有其他内容都将照常运行。 Now, get_int_fptr is a special type for a function returning int and if you assume that *_fptr are all function pointers then you can find what the function signature is by simply looking at the typedef.
现在,get_int_fptr是返回int的函数的特殊类型,如果您假设* _fptr都是函数指针,则只需查看typedef即可找到函数签名。
No, it has to be implemented like this : 不,它必须像这样实现:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.