class Card
{
private:
int face;
char suit;
public:
Card();
Card(char, int);
int getRank() { return face; }
char getSuit() { return suit; }
void setFace(int cardFace) { face = cardFace; }
void setSuit(char cardSuit) { suit = cardSuit; }
};
Card::Card(char cardSuit, int cardFace)
{
face = cardFace;
suit = cardSuit;
}
class Player
{
public:
Player();
vector<Card>allCards;
vector<Card>hand; //holds 7 cards
};
Player::Player()
{
std::random_device seed;
std::mt19937 rng(seed());
for (int i = 1; i <= 13; i++)
{
Card c1('D', i), c2('C', i), c3('H', i), c4('S', i);
allCards.push_back(c1);
allCards.push_back(c2);
allCards.push_back(c3);
allCards.push_back(c4);
}
shuffle(std::begin(allCards), std::end(allCards), rng);
for (int x = 0; x < 7; x++) {
hand[x] = allCards.back(); <---------- Error here
allCards.pop_back();
}
}
我正在尝试使用课程创建一个游戏,在某些时刻我必须为每个玩家分配7张牌,这对我来说并不像我试图管理它那样。
我收到以下错误
Error: Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)
答案 0 :(得分:1)
您忘记初始化hand
向量。默认情况下,它的大小为0
,访问hand[x]
超出范围。
如果你知道它有一个常量,你可以在Player
构造函数的初始化列表中初始化它的大小。
Player::Player() : hand(HAND_SIZE) {
...
}
或者您可以更改代码以使用push_back()
,因为hand
为空,除非另有初始化。
hand.push_back(allCards.back());