结构标记和名称,为什么一个局部变量声明为姓纂? [英] Structure tag and name, why does a local variable declared as name compile?

查看:130
本文介绍了结构标记和名称,为什么一个局部变量声明为姓纂?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一些code我最近看到有这样定义的结构:

In some code I saw recently there was a structure defined like this:

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

我理解这个问题的方法, tagMyStruct 是新的数据类型和 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;

和它编译罚款与Visual Studio 2010中如何是有效的C ++?我以为 MYSTRUCT 是一个变量,而不是一个类型?

and it compiled fine with Visual Studio 2010. How is that valid C++? I thought MYSTRUCT was a variable and not a type?

推荐答案

没有。 tagMyStruct 是结构的名称。在C,不像C ++,你必须明确地使用每次使用结构类型时struct关键字。例如:

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

要避免写结构的时候,结构tagMyStruct 的typedef 倒是为 MYSTRUCT 。现在,你可以写

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;

您认为这是什么(变量定义)将没有typedef关键字,像这样

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

是无效的C或C ++反正。也许你的意思是

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)

心连心

这篇关于结构标记和名称,为什么一个局部变量声明为姓纂?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆