C++ typedef and struct question
typedef struct
{
int y;
int weight;
struct edgenode * next;
}edgenode;
This code is giving error : 'edgenode' : redefinition; different basic types
It works fine in C code.
Why?
Because your struct doesn't have a name! The question suggests a C heritage - the code is written the way I'd write it.
The pure C++ solution is:
struct edgenode
{
int y;
int weight;
edgenode *next;
};
This will not work in C. In C, and consistent with the question, you would write:
typedef struct edgenode
{
int y;
int weight;
struct edgenode * next;
} edgenode;
Now your struct has a name - struct edgenode
. There is also a typedef for it, of course - edgenode
, but the compiler doesn't know about that name until it reaches the final semi-colon (approximately). You could also write:
typedef struct edgenode edgenode;
struct edgenode
{
int y;
int weight;
edgenode *next;
};
try:
struct edgenode
{
int y;
int weight;
edgenode* next;
};
In C++ it is no longer required to use the typedef on struct nodes.
Also the way you were using it (for C) was wrong. if you typedef it then there is no need to use struct anymore.
In C you had 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;
No name specified for your struct before you typedef
typedef struct edgenode
{
int y;
int weight;
edgenode* next;
}en;
The difference between C and C++ is, that they treat struct-names and typedef names differently. In C you can not refer to a struct without using the "struct" keyword unless you create typedef name which resolves to the struct name. Therefore this is valid in C, but not in C++:
struct A {};
typedef int A;
int main()
{
A a;
struct A a;
}
structs and typedefs live in a different namespace if you want to. However in C++, both struct and typedef names go into the same namespace. There can be only one A and therefore this example does not compile. So how does this apply to your example? Let's read it the C way:
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"
This declaration actually created two things called edgenode: A typedef (for the unnamed struct) and an incomplete type "struct edgenode" that is not defined anywhere. You will notice that edgenode x; x.next->y
will not compile.
Here's how C++ reads it:
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!!
精彩评论