在c++中,在哪些情况下使用结构体比使用类更好?
当前回答
我认为Structs是作为一个数据结构(像一个多数据类型的信息数组)和类是为代码打包(像子例程和函数的集合)而设计的。
:(
其他回答
c++中类和结构的区别是:
结构成员和基类/结构在默认情况下是公共的。 默认情况下,类成员和基类/结构是私有的。
类和结构都可以混合使用public、protected和private成员,可以使用继承,也可以有成员函数。
我向你推荐:
对于没有任何类样特性的普通旧数据结构使用struct; 在使用私有或受保护成员、非默认构造函数和操作符等特性时使用类。
它们是一样的,只是默认值不同(class默认为private, struct默认为public),所以理论上它们是完全可以互换的。
所以,如果我只是想打包一些信息来移动,我使用一个结构体,即使我在那里放了一些方法(但不是很多)。如果它是一个最不透明的东西,其中主要使用将通过方法,而不是直接到数据成员,我使用一个完整的类。
只是从c++ 20 standard的角度(从N4860工作)来解决这个问题…
类是一种类型。关键字“class”和“struct”(以及“union”)在c++语法中是“class-key”,选择class或struct的唯一功能意义是:
类键决定是否…默认情况下访问是public或private(11.9)。
数据成员默认可访问性
class关键字的结果是private-by-default成员,而' struct关键字的结果是public-by-default成员,在11.9.1的例子中有说明:
类X { int;// X::a默认为private:使用的类
对…
struct S { int;// S::a默认为public: struct被使用
基类默认可访问性
1.9还说:
在基类没有访问说明符的情况下,当派生类使用类键结构体定义时假定为public,当类使用类键类定义时假定为private。
需要一致使用结构体或类的情况……
有一个要求:
在类模板的重声明、部分特化、显式特化或显式实例化中,类键应与原始类模板声明一致(9.2.8.3)。
...在任何详细类型说明符中,枚举关键字应使用指向枚举(9.7.1),联合类键应使用指向联合(11.5),类或结构的类键必须是 用于指非并体类(11.1)。
以下是不需要一致性的例子:
struct S {} S; 类S* p = &s;/ /好吧
不过,一些编译器可能会对此提出警告。
有趣的是,虽然你用struct、class和union创建的类型都被称为“类”,但我们有…
标准布局结构体是用类键结构体或类键类定义的标准布局类。
...所以在标准语中,当谈到标准布局结构体时,它使用“struct”来暗示“不是联合”。
我很好奇在其他术语中是否也有类似的“struct”用法,但要对标准进行详尽的搜索,工作量太大了。欢迎对此发表评论。
正如其他人指出的那样
除了默认可见性之外,两者都是等效的 无论出于什么原因,都可能有理由被迫使用其中一种或另一种
关于何时使用Stroustrup/Sutter给出了明确的建议:
如果类有不变量,则使用class;如果数据成员可以独立变化,则使用struct
然而,请记住,将某事物前向声明为类(class X;)并将其定义为struct (struct X{…})。 它可能在某些链接器上工作(例如g++),但可能在其他链接器上失败(例如MSVC),所以你会发现自己陷入了开发人员的地狱。
摘自c++ FAQ Lite:
The members and base classes of a struct are public by default, while in class, they default to private. Note: you should make your base classes explicitly public, private, or protected, rather than relying on the defaults. struct and class are otherwise functionally equivalent. OK, enough of that squeaky clean techno talk. Emotionally, most developers make a strong distinction between a class and a struct. A struct simply feels like an open pile of bits with very little in the way of encapsulation or functionality. A class feels like a living and responsible member of society with intelligent services, a strong encapsulation barrier, and a well defined interface. Since that's the connotation most people already have, you should probably use the struct keyword if you have a class that has very few methods and has public data (such things do exist in well designed systems!), but otherwise you should probably use the class keyword.