函数参数中的struct关键字有什么区别?

Sha*_*hay 5 c c++ struct

我想知道,有什么区别:

struct Node
{
  int data;
  Node *next;
};
Run Code Online (Sandbox Code Playgroud)

struct Node
{
  int data;
  struct Node *next;
};
Run Code Online (Sandbox Code Playgroud)

为什么我们struct在第二个例子中需要关键字?

另外,有什么区别

void Foo(Node* head) 
{
    Node* cur = head;
    //....
}
Run Code Online (Sandbox Code Playgroud)

void Foo(struct Node* head) 
{
    struct Node* cur = head;
    //....
}
Run Code Online (Sandbox Code Playgroud)

Mel*_*ius 5

只有包含的声明struct在 C 中有效。在 C++ 中没有区别。

但是,您可以typedef使用structC 语言,因此您不必每次都编写它。

typedef struct Node
{
  int data;
  struct Node *next;  // we have not finished the typedef yet
} SNode;

SNode* cur = head;    // OK to refer the typedef here
Run Code Online (Sandbox Code Playgroud)

为了兼容性,此语法在 C++ 中也有效。

  • *“在 C++ 中没有区别。”* - 这不太正确......接下来是 `struct Node*;` 仅搜索该名称的 `struct`/`class`/`union` 并愉快地忽略非-`struct`/`class`/`union`s 具有相同的标识符。例如,如果你向 `struct Node;` 添加一个 `int Node;` 数据成员,它不会与 `struct Node* next;` 冲突,但会与 `Node* next;` 冲突。但是,没有人理智依赖于这种区别 - 导致无法维护的代码。 (4认同)