在c++中,在哪些情况下使用结构体比使用类更好?
当前回答
我从来不在c++中使用struct。
我无法想象在需要私有成员时使用结构体的场景,除非您故意试图混淆。
使用结构体似乎更像是一种如何使用数据的语法指示,但我宁愿只创建一个类,并尝试在类的名称中显式地表示它,或通过注释。
E.g.
class PublicInputData {
//data members
};
其他回答
它们是一样的,只是默认值不同(class默认为private, struct默认为public),所以理论上它们是完全可以互换的。
所以,如果我只是想打包一些信息来移动,我使用一个结构体,即使我在那里放了一些方法(但不是很多)。如果它是一个最不透明的东西,其中主要使用将通过方法,而不是直接到数据成员,我使用一个完整的类。
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风格的结构体一起工作。
摘自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.
正如其他人所指出的那样,真正的语言差异只有两个:
Struct默认为公共访问,class默认为私有访问。 继承时,struct默认为公共继承,class默认为私有继承。(具有讽刺意味的是,与c++中的许多东西一样,默认是反向的:公共继承是迄今为止更常见的选择,但人们很少声明结构只是为了节省键入“public”关键字。
但在实践中,真正的区别在于声明构造函数/析构函数的类/结构与未声明构造函数/析构函数的类/结构之间的区别。对于“普通的旧数据”POD类型有一定的保证,一旦接管类的构造就不再适用。为了明确这种区别,许多人故意只对POD类型使用结构体,如果他们要添加任何方法,则使用类。下面两个片段之间的区别是没有意义的:
class X
{
public:
// ...
};
struct X
{
// ...
};
(顺便提一句,这里有一个线程,对“POD类型”的实际含义有一些很好的解释:c++中的POD类型是什么?)
当我需要创建POD类型或函子时,我使用结构体。