结构体tag和name,为什么声明为name的局部变量会编译?
在我最近看到的一些代码中,有一个如下定义的结构:
typedef struct tagMyStruct {
int numberOne;
int numberTwo;
} MYSTRUCT;
据我了解,tagMyStruct
是新的数据类型,MYSTRUCT
是在那里创建的变量。
在另一个地方,它是这样使用的:
MYSTRUCT *pStruct = new MYSTRUCT;
并且它在 Visual Studio 2010 中编译得很好。这如何是有效的 C++?我认为 MYSTRUCT 是一个变量而不是类型?
In some code I saw recently there was a structure defined like this:
typedef struct tagMyStruct {
int numberOne;
int numberTwo;
} MYSTRUCT;
The way I understand this, tagMyStruct
is the new data type and MYSTRUCT
is a variable that is created right there.
At another place, this was used like this:
MYSTRUCT *pStruct = new MYSTRUCT;
and it compiled fine with Visual Studio 2010. How is that valid C++? I thought MYSTRUCT
was a variable and not a type?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不。
tagMyStruct
是结构的名称。在 C 中,与 C++ 不同,每次使用结构类型时都必须显式使用 struct 关键字。例如,为了避免始终写入 struct,将
struct tagMyStruct
typedef
转换为MYSTRUCT
。现在你可以写你所认为的(变量定义),而无需使用 typedef 关键字,就像这样顺便
说一句,
无论如何,这都不是有效的 C 或 C++。也许你的意思是
hth
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 exampleTo avoid writing struct all the time,
struct tagMyStruct
istypedef
'd toMYSTRUCT
. Now you can writeWhat you thought this was (a variable definition) would be without the typedef keyword, like this
BTW
is not valid C or C++ anyway. Maybe you mean
hth
定义了一个名为
tagMyStruct
的新 C++ 类型(类)。使用给定的结构定义一个名为 MYSTRUCT 的变量。
定义了一个名为 MYSTRUCT 的 typedef,它相当于给定的匿名结构。
定义了一个名为
MYSTRUCT
的 typedef 和一个名为tagMyStruct
的类型。所以 MYSTRUCT 只是 tagMyStruct 的 typedef。因此,MYSTRUCT pStruct
定义了一个名为pStruct
的tagMyStruct
。您给出的赋值无效,因为
new MYSTRUCT
返回一个指向MYSTRUCT
的指针。defines a new C++ type (class) called
tagMyStruct
.defines a variable called
MYSTRUCT
with the given structure.defines a typedef called
MYSTRUCT
which is equivalent to the given anonymous struct.defines a typedef called
MYSTRUCT
and a type calledtagMyStruct
. So MYSTRUCT is just a typedef for tagMyStruct. Therefore,MYSTRUCT pStruct
defines atagMyStruct
calledpStruct
.The assignment you gave is invalid, since
new MYSTRUCT
returns a pointer toMYSTRUCT
.你错了,你使用的是
typedef
,即MYSTRUCT
是tagMyStruct
的别名。这解释了c++是如何正确的。为了创建变量,删除 typedef:
You are wrong, you are using
typedef
, i.e.MYSTRUCT
is an alias fortagMyStruct
. This explains how it's correct c++.In order to create a variable, drop the typedef: