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

查看:193
本文介绍了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甚至不需要引用先前声明的struct或类)。

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天全站免登陆