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


当前回答

默认情况下,所有类成员都是私有的,所有结构成员都是公共的。 类有默认的私有基,Struct有默认的公共基。Struct在C中不能有成员函数,而在c++中可以有成员函数被添加到Struct中。除了这些差异之外,我没有发现任何令人惊讶的地方。

其他回答

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

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

对于c++来说,结构体和类之间并没有太大的区别。主要的功能区别是,结构的成员在默认情况下是公共的,而在类中默认情况下是私有的。否则,就语言而言,它们是等价的。

也就是说,我倾向于在c++中使用结构体,就像我在c#中做的那样,类似于Brian所说的。struct是简单的数据容器,而类用于对象,除了保存数据外,还需要对数据进行操作。

struct相对于class的一个优点是,如果坚持“首先是public成员,然后是private成员”,它可以节省一行代码。从这个角度来看,我发现关键字class毫无用处。

下面是只使用struct而不使用class的另一个原因。c++的一些代码风格指南建议使用小写字母表示函数宏,其基本原理是当宏转换为内联函数时,不需要更改名称。我也一样。你有了漂亮的c风格结构体,有一天,你发现你需要添加一个构造函数,或者一些方便的方法。你会把它改成一个类吗?到处都是吗?

区分结构体和类实在是太麻烦了,妨碍了我们做应该做的事情——编程。像c++的许多问题一样,它产生于向后兼容的强烈愿望。

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

当你用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的默认保护级别是公共的……