C 与 C++ 中的 struct 和 typedef

2023-07-01C/C++开发问题
2

本文介绍了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 {/* ... *

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6