为什么数据结构中结构体定义时都要写成typedef struct?直接写成struct不就可以吗?

请问定义结构体直接用struct不就可以吗,我知道typedef可以更新结构体名,可是直接用struct不就可以定义吗,为什么前面要加个typedef?这样不是多此一举吗?

在C语言中,如果你这样定义结构体

struct Node
{
    ElemType data;
    struct Node *next;
};

那么声明这种结构体的变量,就必须这样写:

struct Node xxx;

每次都必须在前面加一个struct,这样很麻烦,可以用typedef给这个结构体定义一种类型名:

typedef struct Node
{
    ElemType data;
    struct Node *next;
}MyNode;

那么你现在有了一种新类型叫MyNode,它和int、double、char这些一样都是基本类型,可以直接这样定义这种结构体类型的变量:

MyNode xxx;

不用写前面的struct了(也不能写),省去麻烦。

而C++中,struct和class一样本质上都是类,因此不用使用typedef了,直接定义就可以:

struct Node
{
    ElemType data;
    Node *next;
};

Node xxx;

温馨提示:答案为网友推荐,仅供参考
相似回答