如何在C ++中使用枚举 [英] How to use enums in C++

查看:145
本文介绍了如何在C ++中使用枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个枚举,如下所示:

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;

现在我想使用现有的枚举检查我的变量或实例 value,所以我做:

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

所以要说清楚,说:

if (day == Days.Saturday)         //Causes compilation error

if (day == Saturday)

这两个实际上是指什么,一个是OK,一个导致编译错误?

What do these two actually refer to, in that one is OK and one causes a compilation error?

推荐答案

错误:

enum Days { Saturday,Sunday,Tuesday,Wednesday,Thursday,Friday};
Days day = Days.Saturday;
if(day == Days.Saturday)

由于天不是范围,目的。这是一种类型。而类型本身没有成员。你写的是相当于 std :: string.clear std :: string 是一种类型,因此您不能使用。您在课程的实例上使用

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.

不幸的是,枚举是神奇的所以类比在那里停止。因为有了一个类,你可以执行 std :: string :: clear 来获取一个指向成员函数的指针,但是在C ++ 03中,天::星期日无效。 (这是悲伤的)。这是因为C ++向后兼容C,C没有命名空间,所以枚举必须在全局命名空间中。所以语法很简单:

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)

幸运的是,西摩Seymour 观察到这已经在C ++ 11中得到解决。将枚举更改为枚举类,并获得自己的范围;所以 Days :: Sunday 不仅是有效的,而是只有访问星期日。快乐的时光!

Fortunately, Mike Seymour observes that this has been addressed in 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!

这篇关于如何在C ++中使用枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆