C++ 将枚举作为参数传递
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2870301/
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
C++ pass enum as parameter
提问by Spencer
If I have a simple class like this one for a card:
如果我有这样一个简单的卡片类:
class Card {
public:
enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES };
Card(Suit suit);
};
and I then want to create an instance of a card in another file how do I pass the enum?
然后我想在另一个文件中创建一个卡片的实例如何传递枚举?
#include "Card.h"
using namespace std;
int main () {
Suit suit = Card.CLUBS;
Card card(suit);
return 0;
}
error: 'Suit' was not declared in this scope
错误:“西装”未在此范围内声明
I know this works:
我知道这有效:
#include "Card.h"
using namespace std;
int main () {
Card card(Card.CLUBS);
return 0;
}
but how do I create a variable of type Suit in another file?
但是如何在另一个文件中创建类型为 Suit 的变量?
回答by dash-tom-bang
Use Card::Suit
to reference the type when not inside of Card's scope. ...actually, you should be referencing the suits like that too; I'm a bit surprised that Card.CLUBS
compiles and I always thought you had to do Card::CLUBS
.
用于Card::Suit
在不在 Card 范围内时引用类型。...实际上,你也应该引用这样的套装;我有点惊讶Card.CLUBS
编译,我一直认为你必须这样做Card::CLUBS
。
回答by beeduul
Suit is part of the class Card's namespace, so try:
Suit 是类 Card 命名空间的一部分,所以尝试:
Card::Suit suit = Card::CLUBS;