2010-08-09 78 views
0
typedef struct 
{ 
    int y; 
    int weight; 
    struct edgenode * next; 
}edgenode; 

此代码是给错误:'edgenode' : redefinition; different basic typesC++的typedef和结构问题

它工作在C代码罚款。

为什么?

+0

C++不 “需要” 这种'typedef''ing。 (它有'std :: list'或更适当的'std :: vector'或'std :: deque',你不应该重新制作容器。) – GManNickG 2010-08-09 13:18:02

回答

0

您指定的结构,你的typedef

typedef struct edgenode 
{ 
    int y; 
    int weight; 
    edgenode* next; 
}en; 
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; 
}; 
+0

@Martin(和GMan):我将C++重新组织起来,并指出提问者可能有C背景,因为符号是C风格而不是C++风格。我回去仔细检查标签(和标题);这个问题看起来像C,所以我在几次迭代中添加了C++的东西。现在它组织得更好。感谢提示。 – 2010-08-09 13:26:51

0

尝试:

struct edgenode 
{ 
    int  y; 
    int  weight; 
    edgenode* next; 
}; 

在C++中,它不再需要使用的typedef对结构的节点。
另外你使用它的方式(对于C)是错误的。如果你使用typedef,那么就不需要使用struct了。

在C你有待办事项:

// 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; 
0

C和C之间的差异++是,他们对待结构,名称和typedef名称不同。在C中,如果不使用“struct”关键字,除非您创建了解析为结构名称的typedef名称,否则无法引用结构。因此,这是有效的C,但不是在C++:

struct A {}; 
typedef int A; 

int main() 
{ 
A a; 
struct A a; 
} 

结构和类型定义生活在一个不同的命名空间,如果你想。但是在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:一个类型定义(对于未命名的结构),并且不被任何定义的类型不完全“结构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!!