Structure tag and name, why does a local variable declared as name compile?

随声附和 提交于 2019-12-05 05:19:22

No. tagMyStruct is the name of the struct. In C, unlike C++, you must explicitly use the struct keyword every time you use the struct type. For example

tagMyStruct x; //error
struct tagMyStruct x; //OK

To avoid writing struct all the time, struct tagMyStruct is typedef'd to MYSTRUCT. Now you can write

MYSTRUCT x; //ok, same as struct tagMyStruct x;

What you thought this was (a variable definition) would be without the typedef keyword, like this

struct tagMyStruct {
    int numberOne;
    int numberTwo;
} MYSTRUCT;

BTW

MYSTRUCT pStruct = new MYSTRUCT; //error cannot convert MYSTRUCT* to MYSTRUCT

is not valid C or C++ anyway. Maybe you mean

MYSTRUCT* pStruct = new MYSTRUCT; //valid C++ (invalid C - use malloc instead of new in C)

hth

struct tagMyStruct { ... };

defines a new C++ type (class) called tagMyStruct.

struct { ... } MYSTRUCT;

defines a variable called MYSTRUCT with the given structure.

typedef struct { ... } MYSTRUCT;

defines a typedef called MYSTRUCT which is equivalent to the given anonymous struct.

typedef tagMyStruct struct { ... } MYSTRUCT;

defines a typedef called MYSTRUCT and a type called tagMyStruct. So MYSTRUCT is just a typedef for tagMyStruct. Therefore, MYSTRUCT pStruct defines a tagMyStruct called pStruct.

The assignment you gave is invalid, since new MYSTRUCT returns a pointer to MYSTRUCT.

You are wrong, you are using typedef, i.e. MYSTRUCT is an alias for tagMyStruct. This explains how it's correct c++.

In order to create a variable, drop the typedef:

struct tagMyStruct {
    int numberOne;
    int numberTwo;
} MYSTRUCT;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!