作用域内枚举
发布日期:2021-06-29 11:51:47
浏览次数:2
分类:技术文章
本文共 1112 字,大约阅读时间需要 3 分钟。
传统的枚举存在一些问题,其中之一是两个枚举类型定义中的枚举量可能发生冲突
enum egg {Small, Medium, Large, Jumbo};
enum t_shirt {Small, Medium, Large, Xlarge}; 这将无法通过编译(egg Small和t_shirt Small发生冲突)解决办法(新枚举): C++11提供了一种新枚举,其枚举量的作用域为类:
enum class egg {Small, Medium, Large, Jumbo};
eum class t_shirt {Small, Medium, Large, Xlarge}; 可使用关键字struct代替class 使用时需使用枚举名来限定枚举量:egg choice = egg::Large;
// the Large enumerator of the egg enumt_shirt Floyd = t_shirt::Large;
// the Large enumerator of the t_shirt enumC++11提高了作用域内枚举的类型安全: 有时,常规枚举将自动转换为整型,如将其赋给int变量或用于比较表达式时,但作用域内枚举不能隐式地转换为整型:
enum egg_old {Small, Medium, Large, Jumbo}; // unscoped
enum class t_shirt {Small, Medium, Large, Xlarge}; // scoped
egg_old one = Medium; // unscoped
t_shirt rolf = t_shirt::Large; // scoped
int king = one; // implicit type conversion ofr unscoped
int ring = rolf; // not allowed, no implicit type conversionif (king < Jumbo) // allowed
std::cout<<“Jumbo converted to int before comparison.\n”;if (king < t_shirt::Medium) // not allowed
std::cout<<“Not allowed: < not defined for scoped enum.\n”;但在必要时,可显示类型转换:
int Frodo = int(t_shirt::Small); // Frodo set to 0转载地址:https://blog.csdn.net/ZZHinclude/article/details/114365546 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
第一次来,支持一个
[***.219.124.196]2024年04月06日 03时07分31秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
excel时间日期函数
2019-04-29
excel查找引用函数
2019-04-29
棱镜门事件
2019-04-29
拼多多远程删除用户照片事件
2019-04-29
power BI desktop
2019-04-29
中国信息化发展八大趋势(一)
2019-04-29
中国信息化发展八大趋势(二)
2019-04-29
中国信息化发展八大趋势(三)
2019-04-29
中国信息化发展八大趋势(四)
2019-04-29
电商大战二十年
2019-04-29
神奇的麦考林
2019-04-29
centos7使用rpm安装mysql遇到的error: Failed dependencies: mysql-community-common(x86-64) 5.7.9 is needed
2021-07-02
spark报错:warn util.utils::service ‘sparkUI‘ can not bind on part 4040.Attempting port 4041.4042等错误
2021-07-02
Error getting authority: Error initializing authority: Could not connect: No such file or directory
2021-07-02
编程程软件测试思维方式:如何科学制定测试计划
2021-07-02
raspberry 2b 启动信息
2021-07-02
win7下树莓派安装使用win10
2021-07-02
raspberry 树莓派 360/百度(RT2870 MT7601) WIFI驱动
2021-07-02
raspberrrypi 常用软件大全
2021-07-02