Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/148.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何访问C++;11从另一个文件枚举类?_C++_C++11_Visual C++_Enums - Fatal编程技术网

C++ 如何访问C++;11从另一个文件枚举类?

C++ 如何访问C++;11从另一个文件枚举类?,c++,c++11,visual-c++,enums,C++,C++11,Visual C++,Enums,我有一个头文件,它最终将包含多个枚举类。但是,当我在另一个文件中包含头文件并尝试使用enum类时,我的程序将无法编译。例如: enums.h: #ifndef ENUMS_H #define ENUMS_H enum class TokenType : char { IDEN, STRING, SEMICO }; #endif #ifndef ENUMS_H #define ENUMS_H enum TokenType : char { IDEN,

我有一个头文件,它最终将包含多个枚举类。但是,当我在另一个文件中包含头文件并尝试使用enum类时,我的程序将无法编译。例如:

enums.h:

#ifndef ENUMS_H
#define ENUMS_H

enum class TokenType : char
{
     IDEN,
     STRING,
     SEMICO
};

#endif
#ifndef ENUMS_H
#define ENUMS_H

enum TokenType : char
{
     IDEN,
     STRING,
     SEMICO
}

#endif
和main.cpp:

#include <iostream>
#include "enums.h"

int main()
{
     char token = TokenType::STRING; //Does not compile!
}
#include <iostream>
#include "enums.h"

int main()
{
     char token = STRING; //This does compile!
}
和main.cpp:

#include <iostream>
#include "enums.h"

int main()
{
     char token = TokenType::STRING; //Does not compile!
}
#include <iostream>
#include "enums.h"

int main()
{
     char token = STRING; //This does compile!
}
#包括
#包括“enums.h”
int main()
{
char-token=STRING;//这可以编译!
}

有人知道如何正确地做到这一点吗?我搜索了很多,但什么也没找到。

枚举类
不参与隐式转换,而非范围枚举则参与隐式转换。因此,

int main()
{
     TokenType token = TokenType::STRING;
}
将编译


您可以查看如何以其他方式将
枚举类
转换为其他值。

枚举是强类型,如果不强制转换,则无法将枚举分配给int或char。 您可以尝试:

int main() 
{
  char token = (char)TokenType::STRING; 
}

TokenType
不是
char
,即使其基础类型是。它是自己的类型,不隐式转换。您需要使用正确(
TokenType
)类型的变量或使用显式强制转换。顺便说一句,与旧的
enum
s相比,这是一件好事。如果您必须使用强制转换(总是不喜欢),则更喜欢C++样式强制转换而不是C样式强制转换。在这种情况下,
static\u cast