【问题标题】:Why to use the struct keyword along with structure name in linked list to create pointer of node为什么在链表中使用struct关键字和结构名称来创建节点的指针
【发布时间】:2019-03-23 02:06:03
【问题描述】:
struct linklist
{
    int data;
    struct linklist *next;
}

为什么在*next 前面使用struct linklist?可以简单地通过*node创建一个指针?

【问题讨论】:

标签: c++ struct linked-list structure


【解决方案1】:

可以有同名的函数和结构。要将它们分开,您必须使用关键字struct。

E. g.

struct l {
    int b;
};

void l(struct l &a) {
    a.b = 5;
}

int main () {
    struct l a;
    l(a);

    return 0;
}

在这种情况下,您不能省略关键字struct。但这是一种特殊情况,您可能会在较旧的源代码中找到。

同样在 c 中你需要使用关键字。所以

struct l {};

int main() {
    struct l a;
}

是有效的 c 和 c++ 代码,但是

struct l {};

int main() {
    l a;
}

仅是有效的 c++ 代码。

通常你在 c++ 中不需要那个关键字。

【讨论】:

  • 在 C 中,在结构定义后使用typedef 是很常见的,以避免在使用类型名的任何地方都使用struct 关键字,例如:typedef struct l l; 然后你可以使用@ 987654329@ 而不是 struct l a;
  • @RemyLebeau,是的,你完全正确。但问题是何时以及为什么在 c++ 中使用关键字struct。大约 2 周前我不得不使用它,因为我使用的是一个较旧的 c 库,该库具有同名的函数和结构。
【解决方案2】:

为什么我们在'*next'前面使用struct linklist

您不需要在这里使用详细的类型说明符。所以我想你使用它是因为你可以。

或者您可能打算跨语言边界使用该结构,在这种情况下您使用它是因为有必要在 C 中使用它。

【讨论】:

  • 换句话说,struct 是可选的,但linklist 不是。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-29
  • 1970-01-01
  • 2019-12-26
  • 2020-07-20
  • 2021-09-17
  • 1970-01-01
  • 2016-02-14
相关资源
最近更新 更多