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

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

问题描述

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

Suppose we have an enum like the following:

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

我想创建一个枚举

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";
}

这给我一个编译错误:


错误:'。'之前的预期主表达式

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)

这两个实际上指的是什么,一个是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中, Days ::星期天无效。 (这是悲伤)。这是因为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)

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

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