struct, typedef struct, 在 C++ 中的用途 [英] Purpose of struct, typedef struct, in C++

查看:20
本文介绍了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++ 中的用途的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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