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


当前回答

正如其他人所指出的那样,真正的语言差异只有两个:

Struct默认为公共访问,class默认为私有访问。 继承时,struct默认为公共继承,class默认为私有继承。(具有讽刺意味的是,与c++中的许多东西一样,默认是反向的:公共继承是迄今为止更常见的选择,但人们很少声明结构只是为了节省键入“public”关键字。

但在实践中,真正的区别在于声明构造函数/析构函数的类/结构与未声明构造函数/析构函数的类/结构之间的区别。对于“普通的旧数据”POD类型有一定的保证,一旦接管类的构造就不再适用。为了明确这种区别,许多人故意只对POD类型使用结构体,如果他们要添加任何方法,则使用类。下面两个片段之间的区别是没有意义的:

class X
{
  public:

  // ...
};

struct X
{
  // ...
};

(顺便提一句,这里有一个线程,对“POD类型”的实际含义有一些很好的解释:c++中的POD类型是什么?)

其他回答

类。

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

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表示数据结构,其中成员可以取任何值 那样容易些。

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

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

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

我认为Structs是作为一个数据结构(像一个多数据类型的信息数组)和类是为代码打包(像子例程和函数的集合)而设计的。

:(

摘自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; 在使用私有或受保护成员、非默认构造函数和操作符等特性时使用类。