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


当前回答

正如其他人指出的那样

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

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

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

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

其他回答

正如每个人所说,唯一真正的区别是默认访问。但是,当我不想对简单的数据类进行任何形式的封装时,即使实现了一些helper方法,我也会特别使用struct。例如,当我需要这样的东西时:

struct myvec {
    int x;
    int y;
    int z;

    int length() {return x+y+z;}
};

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

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

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

E.g.

class PublicInputData {
    //data members
 };

摘自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++中类和结构的区别是:

结构成员和基类/结构在默认情况下是公共的。 默认情况下,类成员和基类/结构是私有的。

类和结构都可以混合使用public、protected和private成员,可以使用继承,也可以有成员函数。

我向你推荐:

对于没有任何类样特性的普通旧数据结构使用struct; 在使用私有或受保护成员、非默认构造函数和操作符等特性时使用类。

当我需要创建POD类型或函子时,我使用结构体。