struct and typedef in C versus C++(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
基础教程推荐
- 从 std::cin 读取密码 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01