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


当前回答

正如其他人指出的那样

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

关于何时使用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.

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

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

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

E.g.

class PublicInputData {
    //data members
 };

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

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

在用我的主要语言c++编程多年之后,我得出了一个死结论,那就是这是c++的另一个愚蠢的特性。

两者之间没有真正的区别,我也没有理由花额外的时间来决定是应该将实体定义为结构体还是类。

要回答这个问题,请随时将实体定义为结构。默认情况下,成员将是公开的,这是规范。但更重要的是,默认情况下继承将是公开的。受保护继承和更糟糕的私有继承是例外。

我从来没有遇到过私人继承是正确做法的案例。是的,我试图发明问题来使用私有继承,但它不起作用。如果不使用访问器关键字,面向对象编程的角色模型Java默认为公共继承。顺便提一下,Java不允许在继承类上访问关键字,它们只能被公开继承。所以你可以看到,cpp团队在这里真的很失败。

另一件令人沮丧的事情是,如果你定义为类,声明为结构,你会得到编译警告。就好像这是影响程序性能或准确性的东西一样。一个回答还指出,MSVC可能会产生编译器错误。

Those persons that use classes when it is raining and structs when it is shining are doing so based on what they have been taught. It's not something they discovered to be true. Java does not have a pair of names for classes, and only have the class keyword. If you want a data structure, simply make all your members public and don't add functions. This works in Java and I don't see any problem. What's the problem? You need 4 or 5 characters of BOM code to determine how to interpret the context of a class entity.

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

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

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