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


当前回答

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

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

其他回答

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

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

摘自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有默认的公共基。Struct在C中不能有成员函数,而在c++中可以有成员函数被添加到Struct中。除了这些差异之外,我没有发现任何令人惊讶的地方。

正如其他人指出的那样

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

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

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

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

类。

默认情况下,类成员是私有的。

class test_one {
    int main_one();
};

等于

class test_one {
  private:
    int main_one();
};

所以如果你尝试

int two = one.main_one();

我们将得到一个错误:main_one是私有的,因为它不可访问。我们可以 通过指定它的公共ie来初始化它来解决它

class test_one {
  public:
    int main_one();
};

结构体。

struct是一个类,其成员默认为public。

struct test_one {
    int main_one;
};

意味着main_one是私有的,即

class test_one {
  public:
    int main_one;
};

我用struct表示数据结构,其中成员可以取任何值 那样容易些。