如何在 C++ 中使用枚举

2021-12-29 00:00:00 enums c++

假设我们有一个 enum 如下所示:

Suppose we have an enum like the following:

enum Days {Saturday, Sunday, Tuesday, Wednesday, Thursday, Friday};

我想创建一个这个 enum 的实例并用适当的值初始化它,所以我这样做:

I want to create an instance of this enum and initialize it with a proper value, so I do:

Days day = Days.Saturday;

现在我想用现有的 enum 值检查我的变量或实例,所以我这样做:

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

if (day == Saturday)

?

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

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)

因为 Days 不是范围,也不是对象.它是一种类型.而类型本身没有成员.你写的相当于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 中,Days::Sunday 是无效的.(这是可悲的).这是因为 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)

幸运的是,Mike Seymour 发现 C++11 中已经解决了这个问题.将 enum 更改为 enum class 并获得自己的作用域;所以 Days::Sunday 不仅有效,而且是访问 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!

相关文章