c++ - C 与 C++ 中的 Typedef 结构

标签 c++ c struct typedef

这在 C++ 中会出错,但在 C 中不会:

typedef struct nodes
{
    int data;
    struct node *next;
}node;

它在 C++ 中给出以下错误。

/home/DS cpp/linkedlist.cpp|10|error: conflicting declaration ‘typedef struct nodes node’|
/home/DS cpp/linkedlist.cpp|9|error: ‘struct node’ has a previous declaration as ‘struct node’|
||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

为了让它在 C++ 中工作,我必须将其更改为:

typedef struct node
{
    int data;
    struct node *next;
}node;

我不明白为什么会这样,我想知道 C 和 C++ 中的执行顺序以便我理解。

最佳答案

让我们稍微分析一下你的代码:

typedef struct nodes
{
    int data;
    struct node *next;
}node;

这声明并定义了 struct nodes,一个有两个成员的类型,并声明了一个类型别名,所以我们只能将它称为 node

现在,在 C++ 中,成员声明 struct node *next automatically forward-declares a type called node .这与你的 typedef 目标 node 冲突:就好像你试图给两种类型赋予相同的名称。

在C语言中,不存在冲突,因为称为node的类型实际上只能称为struct node

第二个片段起作用了,因为在解析成员声明期间 struct node 已经存在,没有新类型被前向声明......因为你所做的只是在相同的 typedef 语句,C++ 并不关心,知道它都是相同的类型(struct T is T; 区别在于语法,而不是名称)。

[C++11: 7.1.3/3]: In a given non-class scope, a typedef specifier can be used to redefine the name of any type declared in that scope to refer to the type to which it already refers. [ Example:

typedef struct s { / ... / } s;
typedef int I;
typedef int I;
typedef I I;

—end example ]

[C++11: 7.1.3/6]: In a given scope, a typedef specifier shall not be used to redefine the name of any type declared in that scope to refer to a different type. [ Example:

class complex { / ... / };
typedef int complex; // error: redefinition

—end example ]

当然,在 C++ 中,这一切都没有实际意义,您只需编写:

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

你不需要typedef-去掉elaborated-type-specifier struct

关于c++ - C 与 C++ 中的 Typedef 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31903594/

相关文章:

c++ - Qt5,在lineEdit中设置文字大小

c - C 语言编写的 SDL 程序中的段错误

c - Arduino串口阅读

c++ - 为什么我在打印值时得到垃圾值?

c++ - 如何避免在循环内破坏和重新创建线程?

c++ - 与微软相比,Linux CRunTime 库是如何处理的

c - 二进制文件读取 - 写入不起作用

C结构内存管理

c++ - 将结构数组传递给 pthread_create

c++ - 线程安全的 intrusive_ptr