在 C++ 中使用枚举 class 值调用数组元素

Using enumerated class values to call an array element in C++

我的代码:

Enumerations.h

#ifndef ENUMERATIONS_H
#define ENUMERATIONS_H

enum class Employees
{
    ERIC,
    RYAN,
    EMILY
};

#endif

Structs.h

struct Employee
{
    std::string name;
    double wage;
};

Review.cpp

#include "stdafx.h"
#include <iostream>
#include <string>
#include "Enumerations.h"
#include "Structs.h"

Employee employeeArray[3];

    employeeArray[0] = { "Eric Sartor", 18.75 };
    employeeArray[1] = { "Ryan Ulch", 20.36 };
    employeeArray[2] = { "Emily Gover", 18.75 };

cout << employeeArray[Employees::RYAN].name;

所以我正在尝试做一些我在 C++ 教程中读到的事情,在该教程中您通过枚举值调用数组元素(结构)。在本教程的前面,建议如果您的编译器是 C++11 兼容的(我的也是),那么最好使用枚举 class 而不是常规枚举。

我注意到当尝试通过 Employees::RYAN 枚举值从我的数组中调用我的元素时,它给我一个错误 "expression must have integral or unscoped enum type"。如果我从我的枚举中删除 class 关键字,它只是 enum Employees 并且我将数组索引更改为 RYAN,它工作正常。我是不是遗漏了什么,或者这对枚举 class 不起作用?

希望我说得够清楚。在本教程的示例中,他实际上没有使用枚举 class,只是一个常规枚举,尽管他早些时候明确表示如果可以的话总是这样做......希望有人能为我澄清这一点!

来自 C++ 标准(5.2.1 下标)

1 A postfix expression followed by an expression in square brackets is a postfix expression. One of the expressions shall have the type “array of T” or “pointer to T” and the other shall have unscoped enumeration or integral type....

没有从作用域枚举到整数类型的隐式转换。

如果您想使用范围枚举作为索引,您已将其显式转换为某种整数类型。 例如

cout << employeeArray[static_cast<int>( Employees::RYAN )].name;

枚举键classstruct的枚举是范围枚举。作用域枚举没有隐式转换为 int.

The value of an enumerator or an object of an unscoped enumeration type is converted to an integer by integral promotion (4.5). [ Example:

enum color { red, yellow, green=20, blue };
color col = red;
color* cp = &col;
if (*cp == blue) // ...

makes color a type describing various colors, and then declares col as an object of that type, and cp as a pointer to an object of that type. The possible values of an object of type color are red, yellow, green, blue; these values can be converted to the integral values 0, 1, 20, and 21. Since enumerations are distinct types, objects of type color can be assigned only values of type color.

color c = 1; // error: type mismatch,
// no conversion from int to color
int i = yellow; // OK: yellow converted to integral value 1
// integral promotion

Note that this implicit enum to int conversion is not provided for a scoped enumeration:

enum class Col { red, yellow, green };
int x = Col::red; // error: no Col to int conversion
Col y = Col::red;
if (y) { } // error: no Col to bool conversion

— end example ]

您可以将枚举数显式转换为 int

cout << employeeArray[static_cast<int>(Employees::RYAN)].name;