在 C++ 中什么时候应该使用类还是结构?
在什么情况下,在 C++ 中使用 struct
与使用 class
更好?
In what scenarios is it better to use a struct
vs a class
in C++?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
在什么情况下,在 C++ 中使用 struct
与使用 class
更好?
In what scenarios is it better to use a struct
vs a class
in C++?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(27)
与
class
相比,struct
的一个优点是,如果遵循“先是公共成员,然后是私有成员”,它可以节省一行代码。 从这个角度来看,我发现关键字class
毫无用处。这是仅使用
struct
而从不使用class
的另一个原因。 C++ 的一些代码风格指南建议对函数宏使用小写字母,理由是当宏转换为内联函数时,不需要更改名称。 同样在这里。 您拥有漂亮的 C 风格结构,有一天,您发现需要添加一个构造函数或一些便捷方法。 您是否将其更改为类
? 到处?区分
struct
和class
对于我们应该做的事情——编程来说实在是太麻烦了。 与 C++ 的许多问题一样,它是出于对向后兼容性的强烈渴望而产生的。An advantage of
struct
overclass
is that it save one line of code, if adhering to "first public members, then private". In this light, I find the keywordclass
useless.Here is another reason for using only
struct
and neverclass
. Some code style guidelines for C++ suggest using small letters for function macros, the rationale being that when the macro is converted to an inline function, the name shouldn't need to be changed. Same here. You have your nice C-style struct and one day, you find out you need to add a constructor, or some convenience method. Do you change it to aclass
? Everywhere?Distinguishing between
struct
s andclass
es is just too much hassle getting into the way of doing what we should be doing - programming. Like so many of C++'s problems it arises out of the strong desire for backwards compatibility.struct
和class
在底层是相同的,尽管在可见性方面具有不同的默认值,struct
默认是 public,而class 默认是私有的。 您可以通过适当使用
private
和public
将其中一个更改为另一个。 它们都允许继承、方法、构造函数、析构函数以及面向对象语言的所有其他优点。然而,两者之间的一个巨大区别是,C 中支持
struct
作为关键字,而class
则不支持。 这意味着可以在包含文件中使用struct
,只要该struct
是一个即可#include
到 C++ 或 C 中纯 C 风格struct
以及包含文件中的所有其他内容都与 C 兼容,即没有 C++ 特定关键字,例如private
、public
,没有方法 。AC 风格
struct
可以与支持使用C 风格struct
在接口上来回传输数据的其他接口一起使用AC 风格的 struct 是一种描述内存区域布局的模板(不是 C++ 模板,而是模式或模板)。 多年来,已经创建了可通过 C 语言和 C 插件(这里介绍的是 Java、Python 和 Visual Basic)使用的接口,其中一些接口可与 C 风格的
struct
配合使用。Both
struct
andclass
are the same under the hood though with different defaults as to visibility,struct
default is public andclass
default is private. You can change either one to be the other with the appropriate use ofprivate
andpublic
. They both allow inheritance, methods, constructors, destructors, and all the rest of the goodies of an object oriented language.However one huge difference between the two is that
struct
as a keyword is supported in C whereasclass
is not. This means that one can use astruct
in an include file that can be#include
into either C++ or C so long as thestruct
is a plain C stylestruct
and everything else in the include file is compatible with C, i.e. no C++ specific keywords such asprivate
,public
, no methods, no inheritance, etc. etc. etc.A C style
struct
can be used with other interfaces which support using C stylestruct
to carry data back and forth over the interface.A C style
struct
is a kind of template (not a C++ template but rather a pattern or stencil) that describes the layout of a memory area. Over the years interfaces usable from C and with C plug-ins (here's looking at you Java and Python and Visual Basic) have been created some of which work with C stylestruct
.正如其他人指出的那样,
/Sutter 对于何时使用其中一个有明确的建议:
但是,请记住,转发声明某物是不明智的。 作为类 (
class X;
) 并将其定义为结构 (struct X { ... }
)。它可能在某些链接器(例如,g++)上工作,但在其他链接器(例如,MSVC)上可能会失败,因此您会发现自己陷入了开发者地狱。
As others have pointed out
There's a clear recommendation about when to use which from Stroustrup/Sutter:
However, keep in mind that it is not wise to forward declare sth. as a class (
class X;
) and define it as struct (struct X { ... }
).It may work on some linkers (e.g., g++) and may fail on others (e.g., MSVC), so you will find yourself in developer hell.
它们几乎是同一件事。 感谢 C++ 的魔力,结构可以像类一样保存函数、使用继承、使用“new”创建等等。
唯一的功能区别是类以私有访问权限开头,而结构以公共开头。 这是为了保持与 C 的向后兼容性。
在实践中,我总是使用结构作为数据持有者,使用类作为对象。
They are pretty much the same thing. Thanks to the magic of C++, a struct can hold functions, use inheritance, created using "new" and so on just like a class
The only functional difference is that a class begins with private access rights, while a struct begins with public. This is the maintain backwards compatibility with C.
In practice, I've always used structs as data holders and classes as objects.
当我定义函子和 POD 时,我使用了 struct。 否则我使用
class
。I use
struct
when I definefunctors
andPOD
. Otherwise I useclass
.从技术上讲,两者在 C++ 中是相同的 - 例如,结构可能具有重载运算符等。
但是:
当我希望同时传递多种类型的信息时,我使用结构
当我处理“功能”对象时,我使用类。
希望能帮助到你。
例如,我在此处的 get...() 方法中返回一个 struct Student - 享受吧。
Technically both are the same in C++ - for instance it's possible for a struct to have overloaded operators etc.
However :
I use structs when I wish to pass information of multiple types simultaneously
I use classes when the I'm dealing with a "functional" object.
Hope it helps.
For instance, I'm returning a struct student in the get...() methods over here - enjoy.
默认情况下,结构具有公共访问权限,而类默认具有私有访问权限。
我个人使用结构作为数据传输对象或值对象。 当这样使用时,我将所有成员声明为 const 以防止被其他代码修改。
Structs by default have public access and classes by default have private access.
Personally I use structs for Data Transfer Objects or as Value Objects. When used as such I declare all members as const to prevent modification by other code.
只是从 C++20 标准的角度解决这个问题(来自 N4860)。 ..
类是一种类型。 关键字“
class
”和“struct
”(以及“union
”)在 C++ 语法中是 - class-key< /em>,选择class
或struct
的唯一功能意义是:数据成员默认可访问性
11.9.1 中的示例记录了
class
关键字导致默认私有成员,而 `struct 关键字导致默认公共成员:...vs...
基类默认可访问性
1.9 还说:
需要一致使用结构或类的情况......
有一个要求:
提供了以下示例(当不需要一致性时):
尽管如此,一些编译器可能会对此发出警告。
有趣的是,虽然您使用
struct
、class
和union
创建的类型都称为“类”,但我们......所以在标准语言中,当谈到标准布局结构时,它使用“struct”来暗示“不是联合”。
我很好奇其他术语中是否有类似的“结构”用法,但对标准进行详尽的搜索是一项艰巨的工作。 欢迎评论。
Just to address this from a C++20 Standardese perspective (working from N4860)...
A class is a type. The keywords "
class
" and "struct
" (and "union
") are - in the C++ grammar - class-keys, and the only functional significance of the choice ofclass
orstruct
is:Data member default accessibility
That the
class
keyword results in private-by-default members, and `struct keyword results in public-by-default members, is documented by the examples in 11.9.1:...vs...
Base class default accessibility
1.9 also says:
Circumstances where consistent use of struct or class is required...
There's a requirement:
The following example (of when consistency is not required) is provided:
Still, some compilers may warn about this.
Interestingly, while the types you create with
struct
,class
andunion
are all termed "classes", we have......so in Standardese, when there's talk of a standard-layout struct it's using "struct" to imply "not a union"s.
I'm curious if there are similar use of "struct" in other terminology, but it's too big a job to do an exhaustive search of the Standard. Comments about that welcome.
它们是相同的东西,但默认值不同(
class
默认为 private,struct
默认为 public),因此理论上它们是完全可以互换的。所以,如果我只是想打包一些信息来移动,我会使用一个结构,即使我在那里放置了一些方法(但不是很多)。 如果它是一个大部分不透明的东西,主要用途是通过方法,而不是直接用于数据成员,那么我使用完整的类。
they're the same thing with different defaults (private by default for
class
, and public by default forstruct
), so in theory they're totally interchangeable.so, if I just want to package some info to move around, I use a struct, even if i put a few methods there (but not many). If it's a mostly-opaque thing, where the main use would be via methods, and not directly to the data members, i use a full class.
经过多年使用我的主要语言 C++ 进行编程后,我得出了一个明确的结论:这是 C++ 的另一个愚蠢功能。
两者之间没有真正的区别,我没有理由花额外的时间来决定是否应该将我的实体定义为结构体还是类。
要回答这个问题,请随时将您的实体定义为结构体。 默认情况下,成员将是公开的,这是常态。 但更重要的是,默认情况下继承将是公共的。 受保护的继承,甚至更糟糕的是私有继承,都是例外。
我从来没有遇到过私人继承是正确做法的案例。 是的,我尝试发明问题来使用私有继承,但没有成功。 而 Java,如果不使用访问器关键字,面向对象编程的角色模型默认为公共继承。 顺便说一句,Java 不允许在继承的类上使用访问器关键字,它们只能公开继承。 所以你可以看到,cpp团队在这里真的倒下了。
另一个令人沮丧的事情是,如果您定义为类并声明为结构,则会收到编译警告。 好像这会影响程序的性能或准确性。 一个答案还指出,MSVC 可能会传播编译器错误。
那些下雨时上课、晴天时上课的人,是根据他们所学的内容来这样做的。 他们发现这不是真的。 Java没有一对类名,只有class关键字。 如果您想要一个数据结构,只需将所有成员公开并且不要添加函数即可。 这在 Java 中有效,我没有看到任何问题。 有什么问题? 您需要 4 或 5 个字符的 BOM 代码来确定如何解释类实体的上下文。
After years of programming in C++, my main language, I come to the dead conclusion that this is another one of C++ dumb feature.
There is no real difference between the two, and no reason why I should spend extra time deciding whether I should define my entity as a struct or a class.
To answer this question, feel free to always define your entity as a struct. Members will be public by default which is the norm. But even more importantly, inheritance will be public by default. Protected inheritance, and even worse, private inheritance, are the exceptions.
I have never had a case where private inheritance was the right thing to do. Yes I tried to invent problems to use private inheritance but it didn't work. And Java, the role model of Object Oriented programming defaults to public inheritance if you don't use the accessor keywords. And by the way, Java doesn't allow accessor keywords on inherited classes, they can only be publicly inherited. So you can see, the cpp team really fell down here.
Another frustrating thing about this, is that if you define as a class and declare as a struct you get compilation warning. As though this is something that impacted the performance or accuracy of your program. One answer also noted that MSVC may propogate a compiler error instead.
Those persons that use classes when it is raining and structs when it is shining are doing so based on what they have been taught. It's not something they discovered to be true. Java does not have a pair of names for classes, and only have the class keyword. If you want a data structure, simply make all your members public and don't add functions. This works in Java and I don't see any problem. What's the problem? You need 4 or 5 characters of BOM code to determine how to interpret the context of a class entity.
班级。
类成员默认是私有的。
相当于
所以如果你尝试
我们会得到一个错误:
main_one is private
因为它不可访问。 我们可以通过指定其公共即
结构来初始化它来解决它。
结构体是一个类,其成员默认是公共的。
意味着
main_one
是私有的,即我使用结构作为数据结构,其中成员可以采用任何值,它是
这样更容易。
Class.
Class members are private by default.
Is equivalent to
So if you try
We will get an error:
main_one is private
because its not accessible. We cansolve it by initializing it by specifying its a public ie
Struct.
A struct is a class where members are public by default.
Means
main_one
is private ieI use structs for data structures where the members can take any value, it's
easier that way.
当我需要创建 POD 类型或函子时,我使用结构体。
I use structs when I need to create POD type or functor.
默认情况下,所有类成员都是私有的,所有结构成员默认都是公共的。
类具有默认的私有基,结构具有默认的公共基。 C 的结构不能有成员函数,而 C++ 的结构可以将成员函数添加到结构中。 除了这些差异之外,我没有发现它们有什么令人惊讶的地方。
All class members are private by default and all struct members are public by default.
Class has default private bases and Struct has default public bases. Struct in case of C cannot have member functions where as in case of C++ we can have member functions being added to the struct. Other than these differences, I don't find anything surprising about them.
仅当我需要保存一些没有任何关联成员函数的数据(对成员数据进行操作)并直接访问数据变量时,我才使用 struct。
例如:从文件和套接字流等中读取/写入数据。在函数参数太多且函数语法看起来太长的结构中传递函数参数。
从技术上讲,除了默认的可访问性之外,类和结构之间没有太大区别。
更重要的是,它取决于您如何使用它的编程风格。
I use struct only when I need to hold some data without any member functions associated to it (to operate on the member data) and to access the data variables directly.
Eg: Reading/Writing data from files and socket streams etc. Passing function arguments in a structure where the function arguments are too many and function syntax looks too lengthy.
Technically there is no big difference between class and struture except default accessibility.
More over it depends on programming style how you use it.
我认为结构旨在作为一种数据结构(如多数据类型信息数组),而类则用于代码打包(如子例程和函数的集合)..
:(
I thought that Structs was intended as a Data Structure (like a multi-data type array of information) and classes was inteded for Code Packaging (like collections of subroutines & functions)..
:(
我从不在 C++ 中使用“struct”。
我无法想象当你想要私有成员时你会使用结构的场景,除非你故意试图混淆。
似乎使用结构更多的是如何使用数据的语法指示,但我宁愿创建一个类并尝试在类名称中或通过注释来明确这一点。
例如
I never use "struct" in C++.
I can't ever imagine a scenario where you would use a struct when you want private members, unless you're willfully trying to be confusing.
It seems that using structs is more of a syntactic indication of how the data will be used, but I'd rather just make a class and try to make that explicit in the name of the class, or through comments.
E.g.
正如其他人指出的那样,实际上只有两种实际的语言差异:
struct
默认为公共访问,class
默认为私有访问。struct
默认为public
继承,class
默认为private
继承。 (讽刺的是,与 C++ 中的许多东西一样,默认值是向后的:public
继承是迄今为止更常见的选择,但人们很少声明struct
只是为了节省时间输入“public
”关键字,但实践中真正的区别在于声明构造函数/析构函数的
class
/struct
和不声明构造函数/析构函数的class
/struct
。 “普通旧数据”POD 类型有一些保证,一旦您接管了类的构造,这些保证就不再适用。为了保持这种区别,许多人故意只使用 struct 。对于 POD 类型,如果他们要添加任何方法,请使用class
es。否则下面两个片段之间的差异毫无意义:(顺便说一句,这里有一个带有一些很好解释的线程。关于“POD 类型”的实际含义:C++ 中的 POD 类型是什么? )
As everyone else notes there are really only two actual language differences:
struct
defaults to public access andclass
defaults to private access.struct
defaults topublic
inheritance andclass
defaults toprivate
inheritance. (Ironically, as with so many things in C++, the default is backwards:public
inheritance is by far the more common choice, but people rarely declarestruct
s just to save on typing the "public
" keyword.But the real difference in practice is between a
class
/struct
that declares a constructor/destructor and one that doesn't. There are certain guarantees to a "plain-old-data" POD type, that no longer apply once you take over the class's construction. To keep this distinction clear, many people deliberately only usestruct
s for POD types, and, if they are going to add any methods at all, useclass
es. The difference between the two fragments below is otherwise meaningless:(Incidentally, here's a thread with some good explanations about what "POD type" actually means: What are POD types in C++?)
C++ 中的
class
和struct
之间的区别是:struct
成员和基类/结构是public
默认。class
成员和基类/结构是private
。类和结构都可以混合使用
public
、protected
和private
成员,可以使用继承,并且可以具有成员函数。我建议您:
struct
来表示没有任何类似类功能的普通旧数据结构;private
或protected
成员、非默认构造函数和运算符等功能时,请使用class
。The differences between a
class
and astruct
in C++ are:struct
members and base classes/structs arepublic
by default.class
members and base classes/structs areprivate
by default.Both classes and structs can have a mixture of
public
,protected
andprivate
members, can use inheritance, and can have member functions.I would recommend you:
struct
for plain-old-data structures without any class-like features;class
when you make use of features such asprivate
orprotected
members, non-default constructors and operators, etc.现有的答案存在很多误解。
class
和struct
都声明一个类。< /a>是的,您可能需要重新排列类定义中的访问修改关键字,具体取决于您用来声明该类的关键字。
但是,除了语法之外,选择其中之一的唯一原因是约定/风格/偏好。
有些人喜欢对没有成员函数的类坚持使用
struct
关键字,因为生成的定义“看起来”像 C 中的简单结构。同样,有些人喜欢使用
class
code> 关键字用于具有成员函数和private
数据的类,因为它上面写着“class”,因此看起来像他们最喜欢的面向对象编程书中的示例。现实情况是,这完全取决于您和您的团队,并且它实际上对您的程序没有任何影响。
以下两个类除了名称之外在各方面都绝对等效:
您甚至可以在重新声明时切换关键字:(
尽管这会破坏 Visual Studio 构建< /a> 由于不符合规定,因此当您执行此操作时,编译器将发出警告。)
并且以下表达式的计算结果均为 true:
但请注意,在重新定义<时,您无法切换关键字/em>; 这只是因为(根据单一定义规则)跨翻译单元的重复类定义必须“由相同的标记序列组成”。 这意味着您甚至无法将
const int member;
与int const member;
交换,并且与class
或的语义无关结构
。There are lots of misconceptions in the existing answers.
Both
class
andstruct
declare a class.Yes, you may have to rearrange your access modifying keywords inside the class definition, depending on which keyword you used to declare the class.
But, beyond syntax, the only reason to choose one over the other is convention/style/preference.
Some people like to stick with the
struct
keyword for classes without member functions, because the resulting definition "looks like" a simple structure from C.Similarly, some people like to use the
class
keyword for classes with member functions andprivate
data, because it says "class" on it and therefore looks like examples from their favourite book on object-oriented programming.The reality is that this completely up to you and your team, and it'll make literally no difference whatsoever to your program.
The following two classes are absolutely equivalent in every way except their name:
You can even switch keywords when redeclaring:
(although this breaks Visual Studio builds due to non-conformance, so that compiler will emit a warning when you do this.)
and the following expressions both evaluate to true:
Do note, though, that you can't switch the keywords when redefining; this is only because (per the one-definition rule) duplicate class definitions across translation units must "consist of the same sequence of tokens". This means you can't even exchange
const int member;
withint const member;
, and has nothing to do with the semantics ofclass
orstruct
.结构(POD,更一般地说)当您提供带有 C++ 实现的 C 兼容接口时,它们非常方便,因为它们可以跨语言边界和链接器格式移植。
如果这不是你关心的问题,那么我认为使用“结构”而不是“类”是一个很好的意图沟通者(正如 @ZeroSignal 上面所说)。 结构还具有更可预测的复制语义,因此它们对于您打算写入外部介质或通过网络发送的数据非常有用。
结构对于各种元编程任务也很方便,比如只公开一堆依赖的 typedef 的特征模板:
...但这实际上只是利用了结构的默认保护级别是公共的...
Structs (PODs, more generally) are handy when you're providing a C-compatible interface with a C++ implementation, since they're portable across language borders and linker formats.
If that's not a concern to you, then I suppose the use of the "struct" instead of "class" is a good communicator of intent (as @ZeroSignal said above). Structs also have more predictable copying semantics, so they're useful for data you intend to write to external media or send across the wire.
Structs are also handy for various metaprogramming tasks, like traits templates that just expose a bunch of dependent typedefs:
...But that's really just taking advantage of struct's default protection level being public...
回答我自己的问题(无耻地),正如已经提到的,访问权限是它们在 C++ 中的唯一区别。
我倾向于仅使用结构来存储数据。 如果它能让数据处理变得更容易,我将允许它获得一些辅助函数。 然而,一旦数据需要流控制(即维护或保护内部状态的 getter/setter)或开始获取任何主要功能(基本上更像对象),它将“升级”为一个类,以更好地传达意图。
To answer my own question (shamelessly), As already mentioned, access privileges are the only difference between them in C++.
I tend to use a struct for data-storage only. I'll allow it to get a few helper functions if it makes working with the data easier. However as soon as the data requires flow control (i.e. getters/setters that maintain or protect an internal state) or starts acquring any major functionality (basically more object-like), it will get 'upgraded' to a class to better communicate intent.
对于 C++ 来说,结构和类之间确实没有太大区别。 主要的功能区别在于,结构体的成员默认是公共的,而在类中默认是私有的。 否则,就语言而言,它们是等效的。
也就是说,我倾向于在 C++ 中使用结构,就像在 C# 中一样,类似于 Brian 所说的。 结构是简单的数据容器,而类用于除了保存数据之外还需要对数据进行操作的对象。
For C++, there really isn't much of a difference between structs and classes. The main functional difference is that members of a struct are public by default, while they are private by default in classes. Otherwise, as far as the language is concerned, they are equivalent.
That said, I tend to use structs in C++ like I do in C#, similar to what Brian has said. Structs are simple data containers, while classes are used for objects that need to act on the data in addition to just holding on to it.
结构对我有帮助的一个地方是当我有一个从另一个系统接收固定格式消息(例如串行端口)的系统时。 您可以将字节流转换为定义字段的结构,然后轻松访问这些字段。
显然,这与在 C 中执行的操作相同,但我发现将消息解码为类的开销通常是不值得的。
One place where a struct has been helpful for me is when I have a system that's receiving fixed format messages (over say, a serial port) from another system. You can cast the stream of bytes into a struct that defines your fields, and then easily access the fields.
Obviously, this is the same thing you would do in C, but I find that the overhead of having to decode the message into a class is usually not worth it.
正如大家所说,唯一真正的区别是默认访问权限。 但当我不想用简单的数据类进行任何类型的封装时,我特别使用 struct,即使我实现了一些辅助方法。 例如,当我需要这样的东西时:
As every one says, the only real difference is the default access. But I particularly use struct when I don't want any sort of encapsulation with a simple data class, even if I implement some helper methods. For instance, when I need something like this:
如果您正在编写内部结构为 C++ 的库,但 API 可以由 C 或 C++ 代码调用,则可以在 C++ 中使用“struct”。 您只需创建一个包含向 C 和 C++ 代码公开的结构和全局 API 函数的标头,如下所示:
然后您可以使用 C++ 代码在 C++ 文件中编写函数 bar() 并使其可从 C 和两个世界可以通过声明的结构共享数据。 当然,混合 C 和 C++ 时还有其他注意事项,但这是一个简化的示例。
You can use "struct" in C++ if you are writing a library whose internals are C++ but the API can be called by either C or C++ code. You simply make a single header that contains structs and global API functions that you expose to both C and C++ code as this:
Then you can write a function bar() in a C++ file using C++ code and make it callable from C and the two worlds can share data through the declared struct's. There are other caveats of course when mixing C and C++ but this is a simplified example.
来自 C++ FAQ Lite:
From the C++ FAQ Lite:
我唯一一次使用结构体而不是类是在函数调用中使用函子之前声明函子,并且为了清楚起见而希望最小化语法时。 例如:
The only time I use a struct instead of a class is when declaring a functor right before using it in a function call and want to minimize syntax for the sake of clarity. e.g.: