将枚举类初始化为 null

bmb*_*bmb 1 c++ enums

我想知道是否可以将枚举类初始化为 null。我写了一个简短的例子来说明我要问的问题。

我这里有一个标头定义了一个名为的枚举类ColorOptions

#ifndef COLORS_HPP
#define COLORS_HPP

enum class ColorOptions
{
  RED,
  BLUE
};
#endif
Run Code Online (Sandbox Code Playgroud)

我还有一个类使用此枚举类根据枚举值打印颜色

#include "Colors.hpp"
#include <iostream>

void printColor(ColorOptions col);

int main()
{
  printColor(ColorOptions::RED);
  printColor(ColorOptions::BLUE);
}

void printColor(ColorOptions col)
{
  switch(col)
  {
  case ColorOptions::RED:
    std::cout << "The color is red" << std::endl;
    break;
  case ColorOptions::BLUE:
    std::cout << "The color is blue" << std::endl;
    break;
  default:
    std::cout << "The color is unknown" << std::endl;
  }
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,是否可以将 a 初始化ColorOptionsREDor以外的东西BLUE?我想达到该printColor方法的默认情况,但我不确定是否可以在不向ColorOptions枚举添加其他类型的情况下实现。

Nat*_*ica 5

获取非有效枚举值的方法是使用static_cast. 那看起来像

printColor(static_cast<ColorOptions>(5));
Run Code Online (Sandbox Code Playgroud)

这将输出

The color is unknown
Run Code Online (Sandbox Code Playgroud)

如果您可以使用 C++17,那么您可以做的一件好事是将枚举更改为类似的内容

enum class ColorOptions
{
  NONE,
  RED,
  BLUE
};
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样调用你的函数

printColor({});
Run Code Online (Sandbox Code Playgroud)

这将为您提供隐式值NONE并导致The color is unknown打印。