用适当的方法在C ++中实现类和枚举。
class CrossingGateRoad {
public:
boolean PowerOn(byte relayNumber) {
digitalWrite(relayNumber, RELAY_ON);
return true;
}
boolean PowerOff(byte relayNumber) {
digitalWrite(relayNumber, RELAY_OFF);
return true;
}
};
然后我尝试按如下方式创建枚举:
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
};
在C#中,我会命名我的枚举并指定值:
public enum CommodityIndexSector
{
Currency = 1,
StockIndex = 2,
GovernmentBond = 3,
Metals = 4,
Energy = 5,
Grains = 6,
Softs = 7,
Meats = 8,
Other = 9
}
我会这样访问.... enumname.enumvalue
。
我不能100%确定课程看起来也不错。
答案 0 :(得分:2)
在c ++中enum
值出现在其外部范围内。如果你有
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
};
几乎等同于#define
值。
要在其他地方指定枚举类型,您需要为其命名:
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
};
并且您可以引用特定的枚举类型:
CrossingZones crossingZones = CROSSINGZONE_CLEAR;
关于值的更直观的声明是使用与当前标准相同的枚举类:
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
};
并使用范围:
CrossingZones crossingZones = CrossingZones::CROSSINGZONE_CLEAR;
// ^^^^^^^^^^^^^^^
答案 1 :(得分:0)
在c ++ 11中,您现在可以使用enum class
,也可以为其指定值。但是,您需要使用强制转换来获取值。
enum class Crossing_zone {
clear = 0,
occupied = 2,
exiting = 1
};
int main()
{
auto myenumvar = Crossing_zone::occupied;
return 0;
}
答案 2 :(得分:-1)
您可以使用以下代码声明枚举:
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然后通过以下代码访问其值:
EnumName::CROSSINGZONE_OCCUPIED