C语言 结构中的功能
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4222661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Functions in structure
提问by Shweta
Can structures contain functions?
结构可以包含函数吗?
回答by paxdiablo
No, but they can contain function pointers.
不,但它们可以包含函数指针。
If your intent is to do some form of polymorphism in C then yes, it can be done:
如果您的意图是在 C 中进行某种形式的多态性,那么是的,可以这样做:
typedef struct {
int (*open)(void *self, char *fspec);
int (*close)(void *self);
int (*read)(void *self, void *buff, size_t max_sz, size_t *p_act_sz);
int (*write)(void *self, void *buff, size_t max_sz, size_t *p_act_sz);
// And data goes here.
} tCommClass;
The typedefabove was for a structure I created for a general purpose communications library. In order to initialise the variable, you would:
在typedef上面的是为一个通用的通信库中创建的I结构。为了初始化变量,您将:
tCommClass *makeCommTcp (void) {
tCommClass *comm = malloc (sizeof (tCommClass));
if (comm != NULL) {
comm->open = &tcpOpen;
comm->close = &tcpOpen;
comm->read = &tcpOpen;
comm->write = &tcpWrite;
}
return comm;
}
tCommClass *makeCommSna (void) {
tCommClass *comm = malloc (sizeof (tCommClass));
if (comm != NULL) {
comm->open = &snaOpen;
comm->close = &snaOpen;
comm->read = &snaOpen;
comm->write = &snaWrite;
}
return comm;
}
tCommClass *commTcp = makeCommTcp();
tCommClass *commSna = makeCommSna();
Then, to call the functions, something like:
然后,调用函数,例如:
// Pass commTcp as first params so we have a self/this variable
// for accessing other functions and data area of object.
int stat = (commTcp->open)(commTcp, "bigiron.box.com:5000");
In this way, a single type could be used for TCP, SNA, RS232 or even carrier pidgeons, with exactly the same interface.
通过这种方式,可以将单一类型用于 TCP、SNA、RS232 甚至载波 pidgeon,并具有完全相同的接口。
回答by wkl
edit Cleared up ambiguity with the use of 'data types'
编辑清除了使用“数据类型”的歧义
Not in C. structtypes can only contain data.
不是在 C.struct类型中只能包含数据。
From Section 6.7.2.1 of the ISO C99 Standard.
来自 ISO C99 标准的第 6.7.2.1 节。
A structure or union shall not contain a member with incomplete or function type(hence, a structure shall not contain an instance of itself, but may contain a pointer to an instance of itself), except that the last member of a structure with more than one named member may have incomplete array type; such a structure (and any union containing, possibly recursively, a member that is such a structure) shall not be a member of a structure or an element of an array.
结构或联合不应包含不完整或函数类型的成员(因此,结构不应包含自身的实例,但可以包含指向自身实例的指针),除非结构的最后一个成员具有超过一个命名成员可能有不完整的数组类型;这样的结构(以及任何包含,可能递归地包含这种结构的成员的联合)不应是结构的成员或数组的元素。
回答by Mohit Dabas
No, you cannot. A structure cannot contain a declaration of a function but they can contain a definition of a function. A structure can only contain data types, pointers, pointers to different function. You can make a pointer to a function and then access from the structure.
你不能。结构不能包含函数声明,但可以包含函数定义。一个结构体只能包含数据类型、指针、指向不同函数的指针。您可以创建一个指向函数的指针,然后从结构中访问。
#include<iostream>
#include<cstring>
using namespace std;
struct full_name
{
char *fname;
char *lname;
void (*show)(char *,char*);
};
void show(char *a1,char * a2)
{
cout<<a1<<"-"<<a2<<endl;
}
int main()
{
struct full_name loki;
loki.fname="Mohit";
loki.lname="Dabas";
loki.show=show;
loki.show(loki.fname,loki.lname);
return 0;
}
回答by user513112
In C, structures are allowed to contain on data values and not the function pointers. Not allowed in C. but the following works literally fine when checked with gcc.
在 C 中,允许结构包含数据值而不是函数指针。在 C. 中不允许,但是当使用 gcc 检查时,以下内容确实可以正常工作。
enter code here
#include <stdio.h>
struct st_func_ptr{
int data;
int (*callback) ();
};
int cb(){
printf(" Inside the call back \n");
return 0;
}
int main() {
struct st_func_ptr sfp = {10, cb};
printf("return value = %d \n",sfp.callback());
printf(" Inside main\n");
return 0;
}
So, am confused ...
所以,我很困惑……
回答by Tony
It's all right. In the linux kernel code,you will find many structures contain functions. such as:
没关系。在linux内核代码中,你会发现很多结构都包含函数。如:
/*
* The type of device, "struct device" is embedded in. A class
* or bus can contain devices of different types
* like "partitions" and "disks", "mouse" and "event".
* This identifies the device type and carries type-specific
* information, equivalent to the kobj_type of a kobject.
* If "name" is specified, the uevent will contain it in
* the DEVTYPE variable.
*/
struct device_type {
const char *name;
struct attribute_group **groups;
int (*uevent)(struct device *dev, struct kobj_uevent_env *env);
void (*release)(struct device *dev);
int (*suspend)(struct device * dev, pm_message_t state);
int (*resume)(struct device * dev);
};
回答by user513391
Yes its possible to declare a function and the function definition is not allowed and that should be the function pointer.
是的,可以声明一个函数,但不允许定义函数,这应该是函数指针。
Its based on C99 tagged structure.
它基于 C99 标记结构。
Lokesh V
洛克什五世
回答by Chris Reid
They can, but there is no inherent advantage in usual C programming.
它们可以,但在通常的 C 编程中没有固有的优势。
In C, all functions are in the global space anyway, so you get no information hiding by tucking them in a function. paxdiablo 's example is a way to organize functions into a struct, but you must see has to dereference each one anyway to use it.
在 C 中,无论如何,所有函数都在全局空间中,因此将它们放入函数中不会隐藏任何信息。paxdiablo 的示例是一种将函数组织到结构中的方法,但是您必须看到无论如何都必须取消引用每个函数才能使用它。
The standard organizational structure of C is the File, with the interfaces in the header and the implementations in the source.
C 的标准组织结构是文件,接口在头中,实现在源中。
That is how libc is done and that is how almost all C libraries are done.
这就是 libc 的完成方式,也是几乎所有 C 库的完成方式。
Moder C compilers allow you to define and implement functions in the same source file, and even implement static functions in header files. This unfortunately leads to some confusion as to what goes where, and you can get unusual solutions like cramming functions into structs, source-only programs with no headers, etc. You lose the advantage of separating interface from implementation that way.
现代 C 编译器允许您在同一个源文件中定义和实现函数,甚至可以在头文件中实现静态函数。不幸的是,这会导致一些关于什么去哪里的混淆,并且您可以获得不寻常的解决方案,例如将函数填充到结构中,没有标题的纯源程序等。您失去了以这种方式将接口与实现分离的优势。

