C/C++ 中枚举作为函数参数

Fro*_*art -5 c c++

有人可以给我一个例子,我们真的需要一个枚举作为函数中的参数吗?

jua*_*nza 5

除了使代码更清晰之外,在 C++ 中,它在编译时强制函数适用于一组可能值中的一个:

namespace Foo
{
enum Bar { A, B, C };

void foo(Bar b) { .... }
void foo2(int i) { /* only ints between 0 and 5 make sense */ }
}


int main()
{
  Foo::Bar b = Foo::A;
  Foo::foo(b);   // OK
  Foo::foo(245); // Compile-time error!
  Foo::foo2(6);  // Compiles, triggering some run-time error or UB 
}
Run Code Online (Sandbox Code Playgroud)