有人能给我一个例子,我们真的需要一个枚举作为函数中的参数吗?
最佳答案
除了使代码更清晰之外,在 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
}
关于c++ - C/C++ 中枚举作为函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12234334/