在c++中,在哪些情况下使用结构体比使用类更好?


当前回答

我认为Structs是作为一个数据结构(像一个多数据类型的信息数组)和类是为代码打包(像子例程和函数的集合)而设计的。

:(

其他回答

struct和class在本质上是相同的,尽管在可见性方面有不同的默认值,struct的默认值是公共的,而类的默认值是私有的。您可以通过适当地使用private和public将其中一个更改为另一个。它们都允许继承、方法、构造函数、析构函数以及面向对象语言的所有其他优点。

然而,两者之间的一个巨大区别是C支持struct作为关键字,而class不支持。这意味着可以在包含文件中使用一个可以#include到c++或C中的结构体,只要该结构体是一个普通的C风格结构体,并且包含文件中的其他内容与C兼容,即没有c++特定的关键字,如private, public, no方法,no继承,等等等等。

C风格结构体可以与其他支持使用C风格结构体在接口上来回传输数据的接口一起使用。

C风格结构是一种模板(不是c++模板,而是一种模式或模板),用于描述内存区域的布局。多年来,C语言和C插件(这里是Java、Python和Visual Basic)已经创建了可用的接口,其中一些与C风格的结构体一起工作。

我唯一一次使用结构体而不是类是在函数调用中使用函数子之前声明函数子,为了清晰起见,我想尽量减少语法。例如:

struct Compare { bool operator() { ... } };
std::sort(collection.begin(), collection.end(), Compare()); 

摘自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.

正如其他人指出的那样

除了默认可见性之外,两者都是等效的 无论出于什么原因,都可能有理由被迫使用其中一种或另一种

关于何时使用Stroustrup/Sutter给出了明确的建议:

如果类有不变量,则使用class;如果数据成员可以独立变化,则使用struct

然而,请记住,将某事物前向声明为类(class X;)并将其定义为struct (struct X{…})。 它可能在某些链接器上工作(例如g++),但可能在其他链接器上失败(例如MSVC),所以你会发现自己陷入了开发人员的地狱。

回答我自己的问题(无耻地),正如已经提到的,访问权限是c++中它们之间的唯一区别。

我倾向于仅将结构体用于数据存储。我将允许它获得一些帮助函数,如果它使处理数据更容易的话。然而,一旦数据需要流控制(即维护或保护内部状态的getter /setter)或开始获得任何主要功能(基本上更像对象),它将被“升级”为一个类,以更好地传达意图。