C/C++中Struct和Enum的区别和例子
C++ 中的结构
结构是 C/C++ 中用户定义的数据类型。结构创建一种数据类型,该数据类型可用于将可能不同类型的项目分组为单一类型。 'struct' 关键字用于创建结构。
句法:
struct structureName{
member1;
member2;
member3;
.
.
.
memberN;
};
C++ 中的结构可以包含两种类型的成员:
- 数据成员:这些成员是普通的 C++ 变量。我们可以在 C++ 中创建具有不同数据类型的变量的结构。
- 成员函数:这些成员是普通的 C++ 函数。除了变量,我们还可以在结构声明中包含函数。
C++ 中的枚举
Enum 是枚举的简称。它是一种用户定义的数据类型。它用于定义可以选择的选项列表。一旦声明了枚举,我们就不能改变它的值,编译器会抛出一个错误。两个枚举不能共享相同的名称。
enum enumName{
member1;
member2;
member3;
.
.
.
memberN;
};
结构和枚举之间的区别 Struct only contains parameterized constructors and no destructors. The compiler does not generate a default constructor for a struct.S No. Struct Enum 1 The “struct” keyword is used to declare a structure The “enum” keyword is used to declare enum. 2 The structure is a user-defined data type that is a collection of dissimilar data types. Enum is to define a collection of options available. 3 A struct can contain both data variables and methods. Enum can only contain data types. 4 A struct supports a private but not protected access specifier. Enum does not have private and protected access specifier. 5 The struct cannot be inherited. Enum also does not support Inheritance. 6 Structure supports encapsulation. Enum doesn’t support encapsulation. 7 When 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 Enum does not contain constructors and destructors. 9 The values allocated to the structure are stored in stack memory. The memory to enum data types is allocated in the stack.