错误:未在此范围内声明"enumElement" [英] error: 'enumElement' was not declared in this scope
问题描述
我写了以下小脚本:
#include <string>
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
enum class Day {sunday, monday, thuesday, wednesday, thursday, friday, saturday};
Day unusedDay, today = sunday;
}
但是我有一个问题.当我调试程序时,编译器会说:
But i have a problem. When I debug the programm, the compiler says:
error: 'sunday' was not declared in this scope
但是有我的枚举类.为什么不宣布星期日?我该如何更改?
but there is my enum class. Why sunday isn't declared? How can I change that?
感谢answears:)
Thanks for answears:)
推荐答案
您正在将枚举
与枚举类
混淆.假设您的代码是这样的:
You are confusing an enum
with an enum class
. Suppose your code was this:
enum Day {sunday, monday, thuesday, wednesday, thursday, friday, saturday};
Day unusedDay, today = sunday;
然后将编译上面的代码,因为普通的 enum
具有在全局范围内可见的值,因此您可以像 Day usedDay,today = sunday;
这样访问它们.至于 enum class
es,规则有所不同.为了使您的示例正常工作,您需要编写如下代码:
Then the above code would compile, since normal enum
's have values that are visible globally, so you can access them like Day unusedDay, today = sunday;
. As for enum class
es, the rules differ a little. For your example to work, you would to write the code like this:
enum Day {sunday, monday, thuesday, wednesday, thursday, friday, saturday};
Day unusedDay, today = Day::sunday;
如果您查看 enum
与vs enum类
es的文档,则会看到以下内容:
If you look at the documentation for enum
's vs enum class
es, you see this:
枚举
声明一个无作用域的枚举类型,其基础类型不固定-
Declares an unscoped enumeration type whose underlying type is not fixed -
请注意此处使用 unscoped 一词,这意味着该变量的名称就可用.
Note the use of the word unscoped here meaning the variable is available just with it's name.
枚举类
声明一个作用域枚举类型,其基础类型为int(关键字class和struct完全等效)
declares a scoped enumeration type whose underlying type is int (the keywords class and struct are exactly equivalent)
如此处所示,枚举类
是作用域的,并且只能作为 enumname :: value
;
As seen here, an enum class
is scoped, and accessibly only as enumname::value
;
(源)
这篇关于错误:未在此范围内声明"enumElement"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!