Ошибка времени выполнения при генерации значений объекта в конструкторе объекта, который их агрегирует

Я пишу программу на C ++ для вводного курса, который имитирует игру в покер. Я создал объект карты с целыми числами, чтобы сохранить значение для лица и масти. Затем я создал объект DeckOfCards, который имеет массив C ++ 11 из 52 объектов карт. Я пытаюсь присвоить карточкам их значения и перетасовать колоду в конструкторе deckOfCards. Пройдя несколько тестов, я считаю, что отследил проблему до процесса формирования лица и костюма. Я также пытаюсь поделиться этими объектами с другим классом (Hand), возвращая ссылку на эти объекты в методе dealCard (), но я думаю, что ошибки происходят до создания экземпляра руки. Ошибка возникает в GCC на моей виртуальной машине Arch-Linux и в Visual Studio, поэтому она кажется независимой от компилятора (хотя clang даже не скомпилирует ее).
Конструктор колоды:

DeckOfCards::DeckOfCards(bool startShuffled) //Constructor.
{
/************************************************************
Constructor iterates through the four suits and 13 faces,
generating a card for each combination. This adds up to a
deck of 52 unique cards. By default it shuffles the deck to
prevent accidental usage of an unshuffled deck in a card
game. Passing 'false' as an arguement prevents the initial
shuffle.
************************************************************/
int arrayLoc = 0; //The card being initialized (its a subscript of deck).

for (int i = 0; i < 4; i++) //For each of the four suits.
{
for (int j = 0; j < 13; j++) //For each face in that suit.
{
deck[arrayLoc].setFace(j); //Create a card with that face.
deck[arrayLoc].setSuit(i); //And with that suit.
arrayLoc++; //Then move to the next card.
}
}

currentCard = 0; //Sets the top of the deck.

if (startShuffled)
shuffle(); //Shuffles the deck by default.
}

Отладчик VS2013 говорит, что не может прочитать лицо deck [0] и данные костюма после первой итерации этого цикла. Это действует аналогично для остальных из них. Сама основная программа (не показанная здесь) работает до того момента, когда я пытаюсь сдать карты в руку через массив указателей на колоду, и я думаю, что это связано с неправильной инициализацией во время генерации колод. Я могу предоставить больше кода, если никто не может найти проблему с тем, что у меня здесь.

Получатели / установщики карт:

void Card::setFace(int faceVal)
{
if (faceVal >= 0 && faceVal < 13) //Validates value before setting.
face = faceVal; //Sets the value of Card's face.
else
throw invalid_argument("Face value must be between 0 and 12 (inclusive)");
}

void Card::setSuit(int suitVal)
{
if (suitVal >= 0 && suitVal < 4) //Validates value before setting.
suit = suitVal; //Sets the value of Card's suit.
else
throw invalid_argument("Suit value must be between 0 and 3 (inclusive)");
}

//Getters
int Card::getFace() const //Returns face by value.
{
return face;
}

int Card::getSuit() const //Returns suit by value.
{
return suit;
}

РЕДАКТИРОВАТЬ: (Добавление информации)
У моего ручного класса есть массив из пяти указателей на объекты Card, которые он извлекает из колоды, вызывая метод DeckOfCard dealCard ().

const Card DeckOfCards::dealCard()
{
/*************************************************
If the deck has not depreciated, this returns a
const reference to the card at the top of the deck
and increments to the next card. If it is depreciated
it throws an exception.
*************************************************/
if (moreCards())
{
unsigned int tempCurrentCard = currentCard;
currentCard++;
return deck[tempCurrentCard];
}
else
{
throw invalid_argument("The deck is out of unused cards. Must shuffle to continue.");
}
}

Конструктор руки:

Hand::Hand(const Card &card1, const Card &card2,
const Card &card3, const Card &card4, const Card &card5)
{
/*****************************************************
Constructor initializes a c++11 array of pointers to
card objects.
*****************************************************/

//Initialize the cards in hand. (as pointers)
cardsInHand[0] = &card1;
cardsInHand[1] = &card2;
cardsInHand[2] = &card3;
cardsInHand[3] = &card4;
cardsInHand[4] = &card5;

//Calculate the value of the hand.
calcHandScore();
}

Я создаю экземпляр руки в main, используя myDeck.dealCard () в качестве каждого аргумента в конструкторе руки. Эта передача данных кажется вероятным местом для ошибки.Hand player1(deck.dealCard(), deck.dealCard(), deck.dealCard(), deck.dealCard(), deck.dealCard());
Но это также может быть связано с алгоритмом тасования колоды:

void DeckOfCards::shuffle()
{
/***********************************************************
Shuffles the deck of cards by via a random number generator.
Should be called whenever the current card is the final
card in the deck.
***********************************************************/
srand(time(NULL)); //Creates a random seed for number generation.
int randomValue; //Stores random number for card selection.

//Loops through each card in deck and swaps it with another.
for (int i = 0; i < 52; i++) //Iterates through the deck.
{
randomValue = rand() % 51; //Selects a random card to swap.

if (randomValue != i) //Prevents self assignment.
{
//Swaps the cards values, effectively swapping their locations.
int tempFace = deck[randomValue].getFace(); //Holds a copy of selected card.
int tempSuit = deck[randomValue].getSuit();
deck[randomValue].setFace(deck[i].getFace());
deck[randomValue].setSuit(deck[i].getSuit());
deck[i].setFace(tempFace);
deck[i].setSuit(tempSuit);
}
}

currentCard = 0; //Shuffle resets the "top" of the deck.
}

0

Решение

Это будет звучать глупо, но, пройдя по коду с помощью отладчика, я понял, что логика класса — это все правильно. Проблема заключалась в цикле for внутри другого цикла for, увеличивающего неправильную переменную (т.е. для (int j = 5; я < 52; j ++)).

0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector