Stackoverflow 精彩答案搬运之 Enum类型
来源:互联网 发布:sqlserver置疑的原因 编辑:程序博客网 时间:2024/05/18 12:33
Stackoverflow
精彩答案搬运计划。
原题链接:原题链接
How to use Enums in C++
Problem:
Suppose we have an enum like the following: enum Days { Saturday,Sunday,Tuesday,Wednesday,Thursday,Friday };
I want to create an instance of this enum and initialize it with a proper value, so I do:
Days day = Days.Saturday;
Now I want to check my variable or instance with an existing enum value, so I do:
if(day == Days.Saturday)
{
std::cout<<"Ok its Saturday";
}
Which gives me a compilation error:
error: expected primary-expression before ‘.’ token
So to be clear, what is the difference between saying:
if(day == Days.Saturday)
//causes compilation error
and
if(day == Saturday)
What do these two actually refer to, in that one is OK and one causes a compilation error?
Answer:
This code is wrong:
enum Days { Saturday,Sunday,Tuesday,Wednesday,Thursday,Friday};Days day = Days.Saturday;if(day == Days.Saturday)
Because days is not a scope, nor object. It is a type. And Types themselves don’t have members. What you wrote is the equivalent to std::string.clear. std::string is a type, so you can’t use . on it. You use . on an instance of a class.
Unfortunately, enums are magical and so the analogy stops there. Because with a class, you can do std::string::clear to get a pointer to the member function, but in C++03, Days::Sunday is invalid. (Which is sad). This is because C++ is (somewhat) backwards compatable with C, and C had no namespaces, so enumerations had to be in the global namespace. So the syntax is simply:
enum Days { Saturday,Sunday,Tuesday,Wednesday,Thursday,Friday};Days day = Saturday;if(day == Saturday)
Tips:
Fortunately, your complaint has been addressedin C++11
. Change enum to enum class and it gets its own scope; so Days::Sunday is not only valid, but is the only way to access Sunday. Happy days!
翻译就算了,因为真的太直白了,如果看不明白可以用划词翻译软件对照着看。
- Stackoverflow 精彩答案搬运之 Enum类型
- C++学习之enum类型
- C++学习之enum类型
- java之枚举类型enum
- C++之枚举类型enum
- c/c++之enum类型详解
- java特性之Enum枚举类型
- java关键字之enum枚举类型浅析
- c语言之枚举类型(enum)
- C 语言之枚举类型Enum
- java enum枚举类型 之 括号赋值
- Enum类型
- Enum类型
- Enum 类型
- Enum类型
- enum类型
- enum类型
- enum 类型
- iOS 开发-理解Certificate、AppId和Provisioning Profile
- CSS -webkit-box的属性
- IOS NSArray & NSDictoray -持续更新
- hostapd交叉编译及测试脚本
- 64位操作系统,mysql ODBC 驱动程序和应用程序之间的体系结构不匹配
- Stackoverflow 精彩答案搬运之 Enum类型
- php之curl设置超时实例【转】
- Android抽象布局——include、merge 、ViewStub
- 代码优化要点
- 建立在免费基础上的50个商业模式
- Android 自定义相机保存图片
- ANR 的一个触摸bug转载下。。点击就会出现 error 的bug。。
- datetime
- HTML布局很重要