C++ 的 enum class

等级 4226 次按键

声明强类型的 enum class Color,并用 switch 输出所选值的名称 Green。

C++ 代码

// 限定作用域的枚举:值必须写成 Color::Red,且不会隐式转换为 int
1enum class Color { Red, Green, Blue };
2
// 选择 Green 值
3Color c = Color::Green;
4
// 根据枚举值分支
5switch (c) {
6 case Color::Red: cout << "Red" << endl; break;
// 此 case 匹配并输出 Green;break 跳出 switch
7 case Color::Green: cout << "Green" << endl; break;
8 case Color::Blue: cout << "Blue" << endl; break;
9}

运行结果

Green
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 C++ 代码中需要输入的符号及其出现次数。

  • <× 12
  • :× 11
  • ;× 8
  • "× 6
  • ,× 2
  • {× 2
  • }× 2
  • (× 1
  • )× 1
  • =× 1

C++ 等级 4 的更多代码示例

← 返回 C++ 打字练习