C编程。 如果我需要在头文件(.h)中引用它的实例,如何在.c中隐藏结构的实现
所以我很好奇如果我们需要在头文件中引用它的实例,如何在.c文件中隐藏结构的实现。 例如,我在头文件中有以下结构:
struct List { NodePtr front; };
我想在.c文件中声明NodePtr来隐藏它的实现。 在.c:
struct Node { void *value; struct Node *next; }; typedef struct Node *NodePtr;
但当然比.h文件不知道NodePtr是什么….
我怎么能以正确的方式做到这一点?
像这样的东西应该可以正常工作。 请注意, struct Node
的定义永远不会离开List.c
list.h
#pragma once #include struct List { struct Node *front; }; void list_init(struct List **list); void list_free(struct List *list); void list_insert(struct List *list, void *value); bool list_contains(struct List *list, void *value);
list.c
#include #include #include "list.h" struct Node { void *value; struct Node *next; }; void list_init(struct List **list) { *list = malloc(sizeof(**list)); } void list_free(struct List *list) { struct Node *node = list->front; while (node != NULL) { struct Node *next = node->next; free(node); node = next; } free(list); } void list_insert(struct List *list, void *value) { struct Node *node = malloc(sizeof(*node)); node->value = value; node->next = list->front; list->front = node; } bool list_contains(struct List *list, void *value) { struct Node *node; for (node = list->front; node != NULL; node = node->next) if (node->value == value) return true; return false; }
main.c中
#include #include "list.h" int main() { struct List *l; list_init(&l); int *value_1 = malloc(sizeof(int)); int *value_2 = malloc(sizeof(int)); int *value_3 = malloc(sizeof(int)); list_insert(l, value_1); list_insert(l, value_2); list_insert(l, value_3); printf("Does the list contain value_1: %d\n", list_contains(l, value_1)); printf("Does the list contain null: %d\n", list_contains(l, NULL)); list_free(l); return 0; }
我很可能在这段代码中有一些错误。 如果你看到任何,请随时修复它们。
你有权利说:
typedef struct Node *NodePtr; struct List { NodePtr front; };
这个typedef struct Node *NodePtr;
是一个前瞻性声明 。 只要使用指向类型的指针,就可以使用它。 指针不需要知道类型(类)结构。 编译器很高兴。