这个静态结构的目的是什么?

时间:2015-02-27 14:49:29

标签: c++ c struct

我遇到了下面的代码,我对它的目的感到有些困惑。

struct bob{
    int myNum;
    struct bob * next;
};

static struct bob_stuff{
    int theNum;
    struct bob *lists;
} bob;

我知道第二个结构是静态的并且被初始化为bob结构,但为什么要这样做呢?但我不确定为什么你有2个结构。

2 个答案:

答案 0 :(得分:3)

我认为结构的名称让你感到困惑。

它是单个链表的定义。

第一个结构

struct bob{
    int myNum;
    struct bob * next;
};

定义列表的节点。我会更清楚地用不同的名字重写它

struct Node{
    int value;
    struct Node * next;
};

第二个结构只是定义列表的头部和列表中的节点数(就像我一样)

static struct bob_stuff{
    int theNum;
    struct bob *lists;
} bob;

所以它可以像

一样重写
static struct SingleLinkedList{
    int nodes_count;
    struct Node *head;
} list;

这个抽象列表用作一些Bob东西的容器。:)

答案 1 :(得分:2)

看起来像"模块" (或"类",如果你愿意的话)声明维护一堆单链接的整数列表。

当然命名很糟糕,应该是这样的。

struct list_node {
  int myNum;
  struct list_node *next;
};

static struct {
  int theNum;
  struct list_node *lists;
} listState;

请注意,名称(" struct tag")bob_stuff毫无意义且令人困惑,应该删除。如果你想要一个static,因此是struct类型的本地变量,那么标签很可能无论如何都不会有用。

相关问题