C - 结构内的函数 [英] C - function inside struct
本文介绍了C - 结构内的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在 struct
中分配一个函数,到目前为止我有这个代码:
typedef struct client_t client_t, *pno;结构体client_t{pid_t pid;字符密码[TAM_MAX];//->50 个字符pno 下一个;pno AddClient(){/* 代码 */}};int main(){client_t 客户端;//代码 ..client.AddClient();}
<块引用>
**Error**: *client.h:24:2: error: 预期的 ‘:’, ‘,’, ‘;’, ‘}’ 或 ‘__attribute__’ 在 ‘{’ 标记之前.*
正确的做法是什么?
解决方案
它不能直接完成,但是您可以使用函数指针并显式传递this"来模拟同样的事情.参数:
typedef struct client_t client_t, *pno;结构体client_t{pid_t pid;字符密码[TAM_MAX];//->50 个字符pno 下一个;pno (*AddClient)(client_t *);};pno client_t_AddClient(client_t *self) {/* 代码 */}int main(){client_t 客户端;client.AddClient = client_t_AddClient;//可能真的在某些 init fn 中完成//代码 ..client.AddClient(&client);}
然而,事实证明,这样做并没有真正为您带来很多好处.因此,您不会看到许多以这种方式实现的 C API,因为您也可以只调用外部函数并传递实例.
Im trying to assign a function inside a struct
, 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();
}
**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);
}
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.
这篇关于C - 结构内的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文