繁体   English   中英

C ++ typedef和struct问题

[英]C++ typedef and struct question

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

这段代码给出了错误: 'edgenode' : redefinition; different basic types 'edgenode' : redefinition; different basic types

它在C代码中可以正常工作。

为什么?

因为您的结构没有名字! 这个问题暗示了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;
};

在键入def之前没有为结构指定名称

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

尝试:

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;

C和C ++之间的区别在于,它们以不同的方式对待struct-names和typedef name。 在C语言中, 除非您创建可解析为结构名称的typedef名称, 否则您不能在不使用“ struct”关键字的情况下引用该结构。 因此,这在C中有效,但在C ++中无效:

struct A {};
typedef int A;

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

如果需要的话,struct和typedef可以位于不同的命名空间中。 但是,在C ++中,结构名称和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 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!!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM