My code:
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;
So I'm trying to do something that I read in my C++ tutorial, where you call an array element (a struct) via an enumerated value. Earlier in the tutorial, it's recommended that if you compiler is C++11 compliant (which mine is) that is it better to use an enumerated class rather than a regular enumeration.
I'm noticing that when trying to call my element from my array via the Employees::RYAN enumerated value, it gives me an error that says "expression must have integral or unscoped enum type".  If I remove the class keyword from my enumeration so it's just enum Employees and I change the array index to RYAN, it works fine.  Am I missing something, or does this just not work with an enumerated class?
Hopefully I was clear enough. In the example on the tutorial, he actually DID NOT use an enumerated class, just a regular enumeration, even though he explicitly said earlier to always do that if you can...hopefully someone can clarify this for me!
An enumeration with an enum-key of class or struct is a scoped enumeration. Scoped enumerations don't have an implicit conversion to 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
colas an object of that type, andcpas a pointer to an object of that type. The possible values of an object of typecolorarered,yellow,green,blue; these values can be converted to the integral values0,1,20, and21. Since enumerations are distinct types, objects of typecolorcan be assigned only values of typecolor.color c = 1; // error: type mismatch, // no conversion from int to color int i = yellow; // OK: yellow converted to integral value 1 // integral promotionNote that this implicit
enumtointconversion 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 ]
You can explicitly cast the enumerator to int instead:
cout << employeeArray[static_cast<int>(Employees::RYAN)].name;
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With