typedef struct
{
int y;
int weight;
struct edgenode * next;
}edgenode;
此代码出错:'edgenode' : redefinition; different basic types
它在C代码中工作正常。
为什么?
答案 0 :(得分:7)
因为你的结构没有名字!这个问题暗示了C遗产 - 代码是按照我写的方式编写的。
纯C ++解决方案是:
struct edgenode
{
int y;
int weight;
edgenode *next;
};
这在C中不起作用。在C中,与问题一致,你会写:
typedef struct edgenode
{
int y;
int weight;
struct edgenode * next;
} edgenode;
现在你的结构有一个名字 - struct edgenode
。当然还有一个typedef - edgenode
,但编译器在到达最后的分号(大约)之前不知道该名称。你也可以写:
typedef struct edgenode edgenode;
struct edgenode
{
int y;
int weight;
edgenode *next;
};
答案 1 :(得分:0)
在typedef
之前,没有为结构指定名称typedef struct edgenode
{
int y;
int weight;
edgenode* next;
}en;
答案 2 :(得分:0)
尝试:
struct edgenode
{
int y;
int weight;
edgenode* next;
};
在C ++中,不再需要在struct节点上使用typedef 你使用它的方式(对于C)也是错误的。如果你输入它,那么就不需要再使用struct了。
在C中你有todo:
// In C:
struct X {};
struct X a;
// C with typedef (Notice here that the struct is anonymous)
// Thus it is only accessible via the typedef (but you could give it a name)
typedef struct {} X;
X a;
// In C++ the use of struct is no longer required when declaring the variable.
struct Y {};
Y a;
答案 3 :(得分:0)
C和C ++之间的区别在于,它们以不同的方式处理struct-name和typedef名称。在C中,如果不使用“struct”关键字,则不能引用结构,除非创建解析为结构名称的typedef名称。因此,这在C中有效,但在C ++中则无效:
struct A {};
typedef int A;
int main()
{
A a;
struct A a;
}
如果您愿意,structs和typedef存在于不同的命名空间中。但是在C ++中,struct和typedef名称都进入同一名称空间。只能有一个 A,因此这个例子不能编译。那么这如何适用于您的示例?让我们用C语言阅读:
typedef struct // Here's an unnamed struct
{
int y;
int weight;
struct edgenode * next; // Oh, yes points to some struct called "edgenode" that we don't know of
}edgenode; // and we want to refer to this structs as "edgenode"
此声明实际上创建了名为edgenode的两个事物:一个typedef(用于未命名的struct)和一个未定义的不完整类型“struct edgenode”。您会注意到edgenode x; x.next->y
将无法编译。
以下是C ++如何读取它:
typedef struct // Here's an unnamed struct
{
int y;
int weight;
struct edgenode * next; // Oh, yes points to some struct called "edgenode" that we don't know of
}edgenode; // and we want to refer to this as "edgenode"..HEY WAITASECOND! There's already SOME OTHER THING named edgenode. We know this, because "next" mentioned it!!