Purpose of struct, typedef struct, in C++(struct, typedef struct, 在 C++ 中的用途)
问题描述
在 C++ 中可以创建一个结构体:
In C++ it is possible to create a struct:
struct MyStruct
{
...
}
也可以执行以下操作:
typedef struct
{
...
} MyStruct;
但据我所知,两者之间没有明显区别.哪个更可取?如果没有区别,为什么两种方式都存在?一个在风格或可读性上比另一个更好吗?
And yet as far as I can tell, no discernable difference between the two. Which is preferable? Why do both ways exist if there is no difference? Is one better than the other in style or readability?
推荐答案
typedef 版本是
The typedef version is a special case of
typedef foo bar;
定义了一个新的类型"栏作为 foo 的别名.在您的情况下, foo 恰好是一个结构.在 C 中,这是引入新类型"的唯一方法(在引号中,因为它们并不真正等同于 int、float 和 co).在 C++ 中,这不是那么有用,因为 C++ 旨在使新类型的定义比 C 更容易和更完整(至少在 C++ 开始时),并且 typedef 甚至不需要引用先前声明的结构(或班级).
which defines a new "type" bar as an alias for foo. In your case, foo happens to be a struct. In C, this was the only way to introduce new "types" (in quotes, because they are not really equivalent to int, float and co). In C++, this is not so useful, because C++ was designed to make definition of new types easier and more complete than C (at least at the beginnings of C++), and the typedef is not even necessary to refer to a previously declared struct (or class).
这篇关于struct, typedef struct, 在 C++ 中的用途的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:struct, typedef struct, 在 C++ 中的用途
基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
