Eri*_*tor 5 c++ arrays enums struct c++11
我的代码:
Enumerations.h
#ifndef ENUMERATIONS_H
#define ENUMERATIONS_H
enum class Employees
{
ERIC,
RYAN,
EMILY
};
#endif
Run Code Online (Sandbox Code Playgroud)
Structs.h
struct Employee
{
std::string name;
double wage;
};
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)
所以我正在尝试做一些我在C++教程中读到的东西,你可以通过枚举值调用数组元素(结构).在本教程的前面,建议如果您的编译器符合C++ 11(我的是),那么使用枚举类而不是常规枚举会更好.
我注意到当试图通过Employees::RYAN枚举值从我的数组中调用我的元素时,它给出了一个错误,表示"表达式必须具有整数或未整合的枚举类型".如果我从枚举中删除class关键字所以它只是enum Employees我将数组索引更改为RYAN,它工作正常.我错过了什么,或者这不适用于枚举类?
希望我足够清楚.在本教程的示例中,他实际上并没有使用枚举类,只是一个常规枚举,即使他早先明确说过,如果你可以做到这一点......希望有人可以为我澄清这一点!
用枚举枚举关键的class或struct是一个范围的枚举.Scoped枚举没有隐式转换int.
枚举器的值或未范围的枚举类型的对象通过整数提升(4.5)转换为整数.[例如:
Run Code Online (Sandbox Code Playgroud)enum color { red, yellow, green=20, blue }; color col = red; color* cp = &col; if (*cp == blue) // ...使颜色成为描述各种颜色的类型,然后声明
col为该类型的对象,并cp作为指向该类型对象的指针.类型的对象的可能值color是red,yellow,green,blue; 这些值可以被转换为整数值0,1,20,和21.由于枚举是不同的类型,color因此只能为类型的对象分配类型的值color.Run Code Online (Sandbox Code Playgroud)color c = 1; // error: type mismatch, // no conversion from int to color int i = yellow; // OK: yellow converted to integral value 1 // integral promotion请注意,这隐含
enum对int转换没有提供一个范围的列举:Run Code Online (Sandbox Code Playgroud)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- 结束例子]
您可以显式地将枚举器强制转换为int:
cout << employeeArray[static_cast<int>(Employees::RYAN)].name;
Run Code Online (Sandbox Code Playgroud)