Ç - 内部结构功能 [英] C - function inside struct
问题描述
我试着去建立一个结构内部的功能,到目前为止,我有这个code:
Im trying to create a function inside a structure, so far i have this code:
typedef struct client_t client_t, *pno;
struct client_t
{
pid_t pid;
char password[TAM_MAX]; // -> 50 chars
pno next;
pno AddClient()
{
/* code */
}
};
int main()
{
client_t client;
//code ..
client.AddClient();
}
错误: client.h:24:2:错误:预期':',',',',','}'或'的属性'前'{'令牌。的
Error: client.h:24:2: error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘attribute’ before ‘{’ token.
这是做了正确的方法是什么?
Which is the correct way to do it ?
推荐答案
它不能直接做的,但你可以使用函数指针,明确传递这个参数效仿同样的事情:
It can't be done directly, but you can emulate the same thing using function pointers and explicitly passing the "this" parameter:
typedef struct client_t client_t, *pno;
struct client_t
{
pid_t pid;
char password[TAM_MAX]; // -> 50 chars
pno next;
pno (*AddClient)(client_t *);
};
pno client_t_AddClient(client_t *self) { /* code */ }
int main()
{
client_t client;
client.AddClient = client_t_AddClient; // probably really done in some init fn
//code ..
client.AddClient(&client);
}
事实证明,这样做,但是,并没有真正给你买一个可怕的很多。因此,你不会看到这种风格实现许多C API的,因为你可能也只是调用外部函数,并通过实例。
It turns out that doing this, however, doesn't really buy you an awful lot. As such, you won't see many C APIs implemented in this style, since you may as well just call your external function and pass the instance.
这篇关于Ç - 内部结构功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!