C++ 函数接收枚举作为其参数之一

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6260883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 19:47:43  来源:igfitidea点击:

C++ Function receiving an enum as one of its parameters

c++enums

提问by I Phantasm I

I am trying to make a function receive an enum as one of its parameters. I had the enum as a global but for some reason my other files couldn't change the enum. so I was wondering how do you set an enum as an argument for a function like,

我试图让一个函数接收一个枚举作为它的参数之一。我将枚举作为全局,但由于某种原因,我的其他文件无法更改枚举。所以我想知道如何将枚举设置为函数的参数,例如,

function(enum AnEnum eee);

or is there a better way to solve the above problem?

或者有没有更好的方法来解决上述问题?

Okay a quick rephrasing of my question: I basically have numerous files and I want all of them to have access to my enum and be able to change the state of that enum also the majority of files that should be able to access it are in a class. The way I was attempting to fix this was by passing the enum into the function that needed to access it, I couldn't work out how to go about making a function receive an enum as one of its arguments.

好的,我的问题的快速改写:我基本上有很多文件,我希望所有文件都可以访问我的枚举并能够更改该枚举的状态,并且应该能够访问它的大多数文件都在班级。我试图解决这个问题的方法是将枚举传递给需要访问它的函数,我无法弄清楚如何让函数接收枚举作为其参数之一。

回答by Xeo

If you want to pass a variable that has a value of one of the enums values, this will do:

如果要传递具有枚举值之一的值的变量,则执行以下操作:

enum Ex{
  VAL_1 = 0,
  VAL_2,
  VAL_3
};

void foo(Ex e){
  switch(e){
  case VAL_1: ... break;
  case VAL_2: ... break;
  case VAL_3: ... break;
  }
}

int main(){
  foo(VAL_2);
}

If that's not what you mean, please clarify.

如果这不是你的意思,请澄清。

回答by iammilind

(1) my other files couldn't change the enum

You cannot change enumvalue as they are constants. I think you meant to change the enumvariable value.

你不能改变enum它们的价值constants。我认为您打算更改变enum量值。

(2) how do you set an enum as an argument for a function ?

If you want to changethe value of the enumvariable then pass it by reference

如果要更改enum变量的值,则通过引用传递它

void function (AnEnum &eee)
{
   eee = NEW_VALUE;
}