gpt4 book ai didi

C - 结构内的函数

转载 作者:太空狗 更新时间:2023-10-29 16:16:09 25 4
gpt4 key购买 nike

我试图在 struct 中分配一个函数,到目前为止我有这段代码:

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.*

正确的做法是什么?

最佳答案

它不能直接完成,但您可以使用函数指针模拟同样的事情并显式传递“this”参数:

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,因为您也可以只调用外部函数并传递实例。

关于C - 结构内的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17052443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com