【问题标题】:Struct keyword in function parameters, what is the difference?函数参数中的struct关键字,有什么区别?
【发布时间】:2015-07-01 08:38:10
【问题描述】:

我想知道,有什么区别:

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

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

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

还有,和有什么区别

void Foo(Node* head) 
{
    Node* cur = head;
    //....
}

void Foo(struct Node* head) 
{
    struct Node* cur = head;
    //....
}

【问题讨论】:

标签: c++ c struct


【解决方案1】:

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

但是,您可以在 C 中 typedefstruct,因此您不必每次都编写它。

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

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

【讨论】:

  • “在 C++ 中没有区别。” - 这并不完全正确...... struct Node* next; 仅搜索 struct/class/@ 987654328@ 使用该名称并愉快地忽略具有相同标识符的非struct/class/unions。例如,如果将int Node; 数据成员添加到struct Node;,它不会与struct Node* next; 冲突,但会与Node* next; 冲突。不过,没有人会依赖这种区别——这会导致代码无法维护。
【解决方案2】:

结构节点是我们创建的一种新的用户定义数据类型。与类不同,使用结构的新数据类型是 "struct strct_name" ,即;你需要 struct_name 前面的关键字 struct。 对于类,您不需要在新数据类型名称前使用关键字。 例如;

class abc
{
  abc *next;
};

当你声明变量时

abc x;

而不是结构

abc x;

在结构的情况下。 也明白了,由语句

struct node * next;

我们正在尝试创建一个指向“strcut node”类型变量的指针,在这种情况下称为自引用指针,因为它指向父结构。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-09
    • 2011-11-14
    • 2011-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多