【问题标题】:What is the difference between this two notations?这两种符号有什么区别?
【发布时间】:2021-01-08 10:26:13
【问题描述】:

所以,基本上我想知道这两种符号之间有什么区别(如果有的话):

第一个例子:

struct Node{
int data;
Node* next;
};
Node* head;

第二个例子:

struct Node{
int data;
struct Node* next;
}
struct Node* head;

我只是想知道这两种记法有什么区别,哪一种更好用?

【问题讨论】:

  • 在 C++ 中,没有区别。这两个示例的作用完全相同,变量上的额外struct 关键字是可选的。使用第一种方式,打字更短。但是,在 C 中,还是有区别的。
  • 好的,谢谢。您更喜欢或推荐使用哪种表示法?
  • 第一个在C是非法的。
  • 我明白了,谢谢! :)
  • @MarekR true,但问题被标记为 C++,第一种方式是合法的,在 C+= 中是首选

标签: c++ pointers linked-list


【解决方案1】:

我想知道这两种符号有什么区别(如果有的话)

Node 是类的类型名称。仅当已声明类时才能使用它。示例:

Node* ptr; // won't work without prior declaration
struct Node;

struct Node;
Node* ptr; // works because of prior declaration

struct Node 是使用详细类型说明符的相同类型名称。它本身就是类的声明。示例:

struct Node* ptr; // works without prior declaration

当函数和类同名时,可以使用详细的类型说明符来消除歧义:

struct Node;

void Node();

void foo() {
    Node* ptr;        // this won't work
    struct Node* ptr; // this works
    Node();           // this is a function call
}

鉴于在您的示例中已经声明了类,并且没有模棱两可的函数,除了struct Node 的输入时间长了大约 64% 之外,没有其他区别。

两次使用哪个更好?

你喜欢哪个。你喜欢多打字还是少打字?


关于 C 语言的注意事项:在 C 中,结构不会自动获得类型名称,因此只能使用详细的类型说明符来引用它们,除非使用 typedef 显式地为结构指定了类型名称。这就是为什么您可能会看到在 C 中比在 C++ 中更常用的详细类型说明符,以及在 C++ 中多余的 typedef。

【讨论】:

    猜你喜欢
    • 2014-04-02
    • 2013-09-08
    • 2019-12-11
    • 2019-03-31
    • 2020-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多