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

时间:2012-09-02 08:02:27

标签: c++ c

有人能给我一个例子,我们真的需要一个enum作为函数中的参数吗?

3 个答案:

答案 0 :(得分:4)

除了使代码更清晰之外,在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 
}

答案 1 :(得分:2)

不需要枚举,但它们使软件更具可读性。例如:

void write( const std::string&, bool flush );

现在是主叫方:

write( "Hello World", true );

如果使用了枚举,则在呼叫方面,第二个参数意味着更清楚:

enum flush_type { flush, no_flush };
void write( const std::string&, flush_type flush );

再次呼叫方:

write( "Hello World", flush );

答案 2 :(得分:0)

按钮中的函数setColor,需要获取参数颜色,这应该是枚举。

相关问题