C 与 C++ 中的 struct 和 typedef

struct and typedef in C versus C++(C 与 C++ 中的 struct 和 typedef)

本文介绍了C 与 C++ 中的 struct 和 typedef的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用 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;
};

然后我使用它创建一个实例test 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 struct {//stuff} test;和我的版本有什么区别?

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++ 中,在任何情况下都不需要重复 struct 关键字.请注意,您创建没有名称的 typedef 的示例(即 typedef struct Name{};)是非标准的 AFAIK(如果您使用关键字 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;

上面的代码创建了一个别名为 Name 的未命名结构.您可以像使用 typedef struct Name {/* ... *

本文标题为:C 与 C++ 中的 struct 和 typedef

基础教程推荐