我刚刚开始学习c ++,而且我仍然对头文件和类结构的概念不熟悉。我已经学习Java 2年了,c ++语法和一些操作有不同的行为。
问题在于,我给自己做了一个小小的练习来制作一副纸牌。这是因为我要使代码更清晰,我会使用枚举作为y套装和卡片的价值。然而问题出现在Deck类中,因为我有一种方法用卡片使用向量填充卡片组。但是我已经研究了很多,现在我在c ++中意识到你无法迭代枚举。在任何地方,我看起来人们建议使用枚举,但避免如果我不能通过枚举迭代我怎么可能填充甲板。
我有一个Card头文件和类,如下所示:
#ifndef CARD_H
#define CARD_H
class Card
{
public:
enum Suit{ HEARTS, CLUBS, SPADES, DIAMONDS };
enum Value{TWO ,THREE ,FOUR ,FIVE ,SIX ,SEVEN ,
EIGHT , NINE , TEN ,ACE,KING,QUEEN,JACK};
Card(Suit suit, Value value);
~Card();
Suit GetSuit();
void SetSuit(Suit suit);
Value GetValue();
void SetValue(Value value);
private:
Suit m_cardSuit;
short m_cardValue;
};
#endif
#include "Card.h"
Card::Card(Suit suit,short value){
this->m_cardSuit = suit;
this->m_cardValue = value;
}
void Card::SetSuit(Suit suit){
this->m_cardSuit = suit;
}
//this is needed to get enum from .h class!!
Card::Suit Card::GetSuit(){
return m_cardSuit;
}
short Card::GetValue(){
return m_cardValue;
}
void Card::SetValue(short value){
this->m_cardValue = value;
}
Deck标题和类如下:
#ifndef DECK_H
#define DECK_H
#include <vector>
#include "Card.h"
using namespace std;
class Deck
{
public:
Deck();
Card GetCard(Card& card);
void addCard(Card& card);
void shuffleCards();
vector<Card> drawCards(short cardsToDraw);
void PopulateDeck();
~Deck();
private:
vector <Card>* m_pCards;
short m_NumberOfCards;
short m_MaximumNumberOfCards;
Card m_card;
};
#endif
#include "Deck.h"
Deck::Deck()
{
m_MaximumNumberOfCards = 52;
m_NumberOfCards = 0;
m_pCards = new vector<Card>(52); //creates heap space for 52 cards.
PopulateDeck();
}
Deck::~Deck()
{
}
void Deck::addCard(Card& cardToAdd){
m_pCards->push_back(cardToAdd); //add a card to the deck. same as (*m_pCards).cardToAdd
}
void Deck::PopulateDeck(){
for (int i = 0; i < 13; ++i)
for (int j = 0; j < 4; ++j){
Card card(Card::Suit.[j],Card::Value.[i]);
m_pCards->push_back(card);
}
}
我知道PopulateDeck()方法中的语法不正确。但这是我想弄清楚的问题,作为c ++的新手,我不知道这是否可行。 并且请尝试帮助我解决手头的问题,因为我已经发现枚举不是要重复,但每个人都建议这样做。因此可以通过这种方式创建卡片并将它们添加到卡座中,或者我必须转到另一条路线并使用数组。 谢谢!
答案 0 :(得分:2)
你可以直接做:
void Deck::PopulateDeck(){
for (int i = 0; i < 13; ++i) {
for (int j = 0; j < 4; ++j){
Card card(j, i);
// Or Card card(Card::Suit(j), Card::Value(i))
m_pCards->push_back(card);
}
}
}
或者,强类型:
enum class Suit{ Begin, HEARTS = Begin, CLUBS, SPADES, DIAMONDS, End };
enum class Value{
Begin, TWO = Begin, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN,
JACK, QUEEN, KING, ACE, End
};
Card::Suit& operator ++(Card::Suit& e)
{
e = Card::Suit(int(e) + 1);
return e;
}
Card::Value& operator ++(Card::Value& e)
{
e = Card::Value(int(e) + 1);
return e;
}
void Deck::PopulateDeck(){
for (Card::Value i = Card::Value::Begin; i != Card::Value::End; ++i) {
for (Card::Suit j = Card::Suit::Begin; j != Card::Suit::End; ++j){
Card card(j, i);
m_cards.push_back(card);
}
}
}