C++11强类型枚举如何改写为长尾词?
- 内容介绍
- 相关推荐
本文共计1317个文字,预计阅读时间需要6分钟。
1. Traditional Enumeration Types' Limitations + User-Defined Enumeration Types in C/C++: Enumeration types are user-defined types that consist of a collection of named integral constants. These constants represent a set of values, typically whole numbers, starting from 0 by default. For instance, defining an enumeration type for a distinctive property.
1.传统枚举类型的缺陷
枚举类型是C/C++中用户自定义的构造类型,它是由用户定义的若干枚举常量的集合。枚举值对应整型数值,默认从0开始。比如定义一个描述性别的枚举类型。
enum Gender{Male,Female};
其中枚举值Male被编译器默认赋值为0,Female赋值为1。传统枚举类型在设计上会存在以下几个问题。
(1)同作用域同名枚举值会报重定义错误。传统C++中枚举常量被暴漏在同一层作用域中,如果同一作用域下有两个不同的枚举类型,但含有同名的枚举常量也是会报编译错误的,比如:
enum Fruits{Apple,Tomato,Orange}; enum Vegetables{Cucumber,Tomato,Pepper}; //编译报Tomato重定义错误
其中水果和蔬菜两个枚举类型中包含同名的Tomato枚举常量会导致编译错误。
本文共计1317个文字,预计阅读时间需要6分钟。
1. Traditional Enumeration Types' Limitations + User-Defined Enumeration Types in C/C++: Enumeration types are user-defined types that consist of a collection of named integral constants. These constants represent a set of values, typically whole numbers, starting from 0 by default. For instance, defining an enumeration type for a distinctive property.
1.传统枚举类型的缺陷
枚举类型是C/C++中用户自定义的构造类型,它是由用户定义的若干枚举常量的集合。枚举值对应整型数值,默认从0开始。比如定义一个描述性别的枚举类型。
enum Gender{Male,Female};
其中枚举值Male被编译器默认赋值为0,Female赋值为1。传统枚举类型在设计上会存在以下几个问题。
(1)同作用域同名枚举值会报重定义错误。传统C++中枚举常量被暴漏在同一层作用域中,如果同一作用域下有两个不同的枚举类型,但含有同名的枚举常量也是会报编译错误的,比如:
enum Fruits{Apple,Tomato,Orange}; enum Vegetables{Cucumber,Tomato,Pepper}; //编译报Tomato重定义错误
其中水果和蔬菜两个枚举类型中包含同名的Tomato枚举常量会导致编译错误。

