📜  C/C++中Struct和Enum的区别和例子

📅  最后修改于: 2022-05-13 01:55:34.171000             🧑  作者: Mango

C/C++中Struct和Enum的区别和例子

C++ 中的结构

结构是 C/C++ 中用户定义的数据类型。结构创建一种数据类型,该数据类型可用于将可能不同类型的项目分组为单一类型。 'struct' 关键字用于创建结构。

句法:

C++ 中的结构可以包含两种类型的成员:

  • 数据成员:这些成员是普通的 C++ 变量。我们可以在 C++ 中创建具有不同数据类型的变量的结构。
  • 成员函数:这些成员是普通的 C++ 函数。除了变量,我们还可以在结构声明中包含函数。

C++ 中的枚举

Enum 是枚举的简称。它是一种用户定义的数据类型。它用于定义可以选择的选项列表。一旦声明了枚举,我们就不能改变它的值,编译器会抛出一个错误。两个枚举不能共享相同的名称。

结构和枚举之间的区别

S No.StructEnum
1The “struct” keyword is used to declare a structureThe “enum” keyword is used to declare enum.
2The structure is a user-defined data type that is a collection of dissimilar data types.Enum is to define a collection of options available.
3A struct can contain both data variables and methods. Enum can only contain data types.
4A struct supports a private but not protected access specifier.Enum does not have private and protected access specifier.
5The struct cannot be inherited.Enum also does not support Inheritance.
6Structure supports encapsulation.Enum doesn’t support encapsulation.
7When the structure is declared, the values of its objects can be modified.Once the enum is declared, its value cannot be changed, otherwise, the compiler will throw an error.
8

Struct only contains parameterized constructors and no destructors. 

The compiler does not generate a default constructor for a struct.

Enum does not contain constructors and destructors.
9The values allocated to the structure are stored in stack memory.The memory to enum data types is allocated in the stack.