结构和类型定义用C与C ++ [英] struct and typedef in C versus C++

查看:168
本文介绍了结构和类型定义用C与C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前使用的是C ++ IDE的东西,就需要基于C的工作,并希望确保我不会有后面这个问题。做下面的结构之后:

I am currently using a C++ IDE for something that will need to work on C, and wanted to make sure that I won't have problems with this later on. After making the struct below:

typedef struct test {
   int a;
   int b;
};

然后我用创建它的一个实例
测试my_test; 然后东西像 my_test.a = 5 ,等等...这工作在我VStudio C细++ 。
这是怎么回事就 GCC 以后的工作?

I then create an instance of it using test my_test; then stuff like my_test.a = 5, etc... and this works fine in my VStudio C++. Is this going to work on gcc later on?

我读到弹出(我看我不是第一个人以这种问题,要么)相关的问题,但似乎没有人用我做的方式。

I read the related questions that popped up (I see I am not the first person with this kind of question, either) but no one seemed to use the way I did.

其实,之间有什么 typedef结构{//}东东测试的区别; 和我的版本

In fact, what is the difference between typedef struct {//stuff} test; and my version?

推荐答案

的区别:

struct Name {};

typedef struct Name {} Name;

是,在C,你需要使用:

Is that, in C, you need to use:

struct Name instance_name;

对于前者,而后者则可能做的:

With the former, whereas with the latter you may do:

Name instance_name;

在C ++中,这是没有必要重复结构关键字在任一情况下。请注意,您的例子中,你创建一个typedef没有名称(即 typedef结构名称{}; )是非标准的AFAIK(如果你使用关键字的typedef ,那么你就需要提供一个别名其中的typedef这个名字)。

In C++, it is not necessary to repeat the struct keyword in either case. Note that your example in which you create a typedef with no name (i.e. typedef struct Name{};) is non-standard AFAIK (if you use the keyword typedef, then you need to supply an alias to which to typedef that name).

至于最后变更:

typedef struct { /* ... */ } Name;

上面的code创建一个别名名称未命名的结构。你会使用这样的结构只是你会与以同样的方式typedef结构名称{/ * ... * /}名称; ,但是编译器通常发射结构的名称(不是别名),所以你可以,如果你给它一个名字,并得到涉及结构更好的错误信息的typedef的,而不是typedef'ing匿名结构。

The code above creates an unnamed struct that is aliased to Name. You would use such a struct just the same way you would with typedef struct Name { /* ... */ } Name;, however compilers often emit the name of the struct (not the alias), and so you may get better error messages involving the struct if you give it a name and typedef that as opposed to typedef'ing an anonymous struct.

这篇关于结构和类型定义用C与C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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