[英]C++ How do I go about setting a point in a string array to an enum variable
So what I am attempting to do is randomly populate a string array with a deck of cards.所以我试图做的是用一副纸牌随机填充一个字符串数组。 I am attempting to do this by "randomly" creating a number between 0-51 so that my array at that location will equal that enum suit followed by the enum value.我试图通过“随机”创建一个介于 0-51 之间的数字来做到这一点,这样我在该位置的数组将等于枚举套装后跟枚举值。 So looking at my code you can see that the way I am setting the value in my array will cause an error.因此,查看我的代码,您可以看到我在数组中设置值的方式会导致错误。 How do I go about accomplishing this while keeping the enumeration?我如何在保持枚举的同时完成此任务?
class DeckOfCards{
private:
string deck[52];
int sCount = 0;
int vCount = 0;
enum Suits{hearts, diamonds, clubs, spades};
enum Value{two, three, four, five, six, seven, eight, nine, ten, jack, queen, king, ace};
public:
DeckOfCards(){
deck[52];
}
void shuffle(DeckOfCards noShuff){
srand(time(nullptr));
for(int i = 0; i < 52; i++){
deck[rand() % 52] = Suits[sCount] + Value[vCount];
sCount++;
vCount++;
}
}
};
Your first issue here is that you are attempting to reference the enum values of Suites
and Value
incorrectly.您的第一个问题是您试图错误地引用Suites
和Value
的枚举值。 Value[0]
will not compile, but Value::two
will. Value[0]
不会编译,但Value::two
会。 Since this is not an enum class, 0
is also equivalent to Value::two
(just as 1
is equivalent to Value::three
).由于这不是枚举 class,因此0
也等同于Value::two
(正如1
等同于Value::three
)。
Without solving the other issues in the code (like sCount
and vCount
not being bounded by the size of Suits
and Value
), you can try deck[rand() % 52] = static_cast<char>(sCount + vCount)
.如果不解决代码中的其他问题(例如sCount
和vCount
不受Suits
和Value
的大小限制),您可以尝试deck[rand() % 52] = static_cast<char>(sCount + vCount)
。
However, I do strongly recommend you abstract the "Card" to a class instead of using std::string
(see below).但是,我强烈建议您将“卡片”抽象为 class 而不是使用std::string
(见下文)。
class Card {
...
};
class DeckOfCards{
private:
Card deck[52]; <-- Deck of "Cards"
...
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.