这在 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, atypedef
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, atypedef
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/