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


当前回答

默认情况下,结构具有公共访问权限,类具有私有访问权限。

就我个人而言,我使用结构作为数据传输对象或作为值对象。当这样使用时,我将所有成员声明为const,以防止其他代码修改。

其他回答

当你用c++实现提供兼容C的接口时,struct(更一般地说是PODs)非常方便,因为它们可以跨语言边界和链接器格式移植。

如果您不关心这一点,那么我认为使用“struct”而不是“class”是一种很好的意图交流方式(如上面的@ZeroSignal所述)。struct还具有更可预测的复制语义,因此对于打算写入外部媒体或通过网络发送的数据非常有用。

struct对于各种元编程任务也很方便,比如trait模板只暴露了一堆依赖的typedef:

template <typename T> struct type_traits {
  typedef T type;
  typedef T::iterator_type iterator_type;
  ...
};

...但这实际上只是利用了struct的默认保护级别是公共的……

正如其他人指出的那样

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

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

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

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

我从来不在c++中使用struct。

我无法想象在需要私有成员时使用结构体的场景,除非您故意试图混淆。

使用结构体似乎更像是一种如何使用数据的语法指示,但我宁愿只创建一个类,并尝试在类的名称中显式地表示它,或通过注释。

E.g.

class PublicInputData {
    //data members
 };

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

:(

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