C++ 中的枚举:如何作为参数传递?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5357053/
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
Enum in C++: how to pass as parameter?
提问by polemon
I have in my class definition the following enum:
我在我的类定义中有以下枚举:
static class Myclass {
...
public:
enum encoding { BINARY, ASCII, ALNUM, NUM };
Myclass(Myclass::encoding);
...
}
Then in the method definition:
然后在方法定义中:
Myclass::Myclass(Myclass::encoding enc) {
...
}
This doesn't work, but what am I doing wrong? How do I pass an enum member correctly, that is defined inside a class for member methods (and other methods as well)?
这不起作用,但我做错了什么?如何正确传递枚举成员,该成员是在成员方法(以及其他方法)的类中定义的?
回答by paulcam
I'm not entirely sure why you're using "static class" here. This boilerplate works just fine for me in VS2010:
我不完全确定你为什么在这里使用“静态类”。这个样板在 VS2010 中对我来说很好用:
class CFoo
{
public:
enum Bar { baz, morp, bleep };
CFoo(Bar);
};
CFoo::CFoo(Bar barIn)
{
barIn;
}
回答by GManNickG
This code is fine:
这段代码很好:
/* static */ class Myclass
{
public:
enum encoding { BINARY, ASCII, ALNUM, NUM };
Myclass(Myclass::encoding); // or: MyClass( encoding );
encoding getEncoding() const;
}; // semicolon
Myclass::Myclass(Myclass::encoding enc)
{ // or: (enum Myclass::encoding enc), they're the same
// or: (encoding enc), with or without the enum
}
enum Myclass::encoding Myclass::getEncoding() const
//or Myclass::encoding, but Myclass:: is required
{
}
int main()
{
Myclass c(Myclass::BINARY);
Myclass::encoding e = c.getEncoding();
}
Update your question with the real code and errors you're getting so we can solve real problems instead of fake ones. (Give us a * compilable* example that reproduces your problem.)
用真实的代码和你得到的错误更新你的问题,这样我们就可以解决真正的问题而不是虚假的问题。(给我们一个*可编译*的例子来重现你的问题。)
回答by J T
class Myclass {
...
public:
enum encoding { BINARY, ASCII, ALNUM, NUM };
Myclass(enum Myclass::encoding);
...
}
Myclass::Myclass(enum Myclass::encoding enc) {
...
}
Just just forgot the enum keyword in the parameter.
只是忘记了参数中的 enum 关键字。
回答by littleadv
Remove the static
. Generally, mentioning the exact error will help you get better answers.
删除static
. 通常,提及确切的错误将帮助您获得更好的答案。
回答by Brian Roach
See this:
看到这个:
You reference it differently depending on the scope. In your own class you say
您根据范围不同地引用它。在你自己的课上你说
Myclass(encoding e);