Reputation: 5162
Struggling a bit with the proper way to implement a class and an enum in C++.
class CrossingGateRoad {
public:
boolean PowerOn(byte relayNumber) {
digitalWrite(relayNumber, RELAY_ON);
return true;
}
boolean PowerOff(byte relayNumber) {
digitalWrite(relayNumber, RELAY_OFF);
return true;
}
};
and then I'm trying to create an enum as follows:
enum {
CROSSINGZONE_CLEAR, // no train in crossing area, also initialized state
CROSSINGZONE_OCCUPIED, // train detected by the entry sensor
CROSSINGZONE_EXITING // train detected by the exit sensor, when sensor clears, state = CLEAR
};
In C# I would name my enum and specify the values:
public enum CommodityIndexSector
{
Currency = 1,
StockIndex = 2,
GovernmentBond = 3,
Metals = 4,
Energy = 5,
Grains = 6,
Softs = 7,
Meats = 8,
Other = 9
}
and I would access it like so.... enumname.enumvalue
.
I'm not 100% sure the class looks right either.
Upvotes: 0
Views: 104
Reputation: 656
You can use the following code to declare the enum:
typedef enum {
CROSSINGZONE_CLEAR, // no train in crossing area, also initialized state
CROSSINGZONE_OCCUPIED, // train detected by the entry sensor
CROSSINGZONE_EXITING // train detected by the exit sensor
} EnumName;
abd then access to its values through the following code:
EnumName::CROSSINGZONE_OCCUPIED
Upvotes: -1
Reputation: 1
In c++ enum
values appear at their outer scope. If you have
enum {
CROSSINGZONE_CLEAR, // no train in crossing area, also initialized state
CROSSINGZONE_OCCUPIED, // train detected by the entry sensor
CROSSINGZONE_EXITING // train detected by the exit sensor, when sensor clears, state = CLEAR
};
pretty much equivalent to have #define
values.
To specify an enum type somewhere else you need to name it:
enum CrossingZones {
// ^^^^^^^^^^^^^
CROSSINGZONE_CLEAR, // no train in crossing area, also initialized state
CROSSINGZONE_OCCUPIED, // train detected by the entry sensor
CROSSINGZONE_EXITING // train detected by the exit sensor, when sensor clears, state = CLEAR
};
and you can reference the specific enum type:
CrossingZones crossingZones = CROSSINGZONE_CLEAR;
A more intuitive declaration regarding the values, is to have enum class as for the current standard:
enum class CrossingZones {
// ^^^^^
CROSSINGZONE_CLEAR, // no train in crossing area, also initialized state
CROSSINGZONE_OCCUPIED, // train detected by the entry sensor
CROSSINGZONE_EXITING // train detected by the exit sensor, when sensor clears, state = CLEAR
};
and use these from scope:
CrossingZones crossingZones = CrossingZones::CROSSINGZONE_CLEAR;
// ^^^^^^^^^^^^^^^
Upvotes: 2
Reputation: 11002
In c++11 you can now use enum class
and you may also specify the values for it. However you will need a cast to get the value back.
enum class Crossing_zone {
clear = 0,
occupied = 2,
exiting = 1
};
int main()
{
auto myenumvar = Crossing_zone::occupied;
return 0;
}
Upvotes: 0