C++传递枚举作为参数
如果我有一个像这样的卡类的简单类:
class Card {
public:
enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES };
Card(Suit suit);
};
然后我想在另一个文件中创建卡的实例,如何传递枚举?
#include "Card.h"
using namespace std;
int main () {
Suit suit = Card.CLUBS;
Card card(suit);
return 0;
}
错误:“Suit”未在此范围内声明
我知道这是可行的:
#include "Card.h"
using namespace std;
int main () {
Card card(Card.CLUBS);
return 0;
}
但是如何在另一个文件中创建 Suit 类型的变量?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当不在 Card 范围内时,使用 Card::Suit 来引用类型。 ...实际上,您也应该引用类似的套装;我对
Card.CLUBS
编译感到有点惊讶,我一直认为您必须执行Card::CLUBS
。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 thatCard.CLUBS
compiles and I always thought you had to doCard::CLUBS
.Suit 是 Card 类命名空间的一部分,因此请尝试:
Suit is part of the class Card's namespace, so try: