【发布时间】:2012-10-21 03:11:13
【问题描述】:
我正在尝试编写二十一点游戏。我在业余时间一直在自学 C++,这是我第一次在任何网站上发布有关编程的文章。
我一直在寻找问题的答案,并且学到了很多东西。但是这个问题完全让我感到困惑。我担心我在完成任务时完全错误,希望你能帮助我。
我有一个 Card 类和一个包含 52 个 Card 的向量的 Deck 类。向量是 Deck 类的私有成员,我担心这是我的问题?
当我将 random_shuffle 行添加到我的代码中时,它可以正常编译,但随后控制台窗口崩溃(Windows 7 x64、code::blocks、c++)。我无法弄清楚我做错了什么。我将向量随机访问迭代器称为 begin() 和 end()...
deck.h
#ifndef DECK_H
#define DECK_H
#include <vector>
using namespace std;
/** Card Class */
class Card
{
public:
/** Constructor prototypes */
//Card(); //default constructor
Card(int s, int r) : suit(s), rank(r) {}
/** GET function prototypes */
int getRank(); // returns card number as int
string getSuit(); // returns the suit in a string
private:
int rank;
int suit;
} ;
/** Deck class */
class Deck
{
public:
Deck();
vector <Card> get_deck() { return deck; };
private:
vector<Card> deck;
};
#endif // DECK_H
deck.cpp
#include <iostream>
#include <string>
#include <vector>
#include "deck.h"
using namespace std;
/** Deck ctor to initialise deck */
Deck::Deck()
{
for(int suit = 0; suit < 4; suit++)
{
for(int rank = 0; rank < 13; rank++)
{
deck.push_back(Card(suit,rank));
}
}
}
/** Functions to GET rank and suit */
// Function to get rank as int
int Card::getRank()
{
return rank;
}
// Function to get suit as string
string Card::getSuit()
{
switch(suit)
{
case 0:
return "Diamonds";
case 1:
return "Hearts";
case 2:
return "Clubs";
case 3:
return "Spades";
default:
return "Error";
}
}
main.cpp
#include <iostream>
#include <algorithm>
#include <ctime> // time()
#include <string>
#include <vector>
#include "deck.h"
using namespace std;
int main()
{
Deck mydeck;
random_shuffle( mydeck.get_deck().begin(), mydeck.get_deck().end() );
// Loop to iterate through deck of cards
for(int i = 0; i<52; i++)
{
cout << mydeck.get_deck()[i].getRank() << " of " << mydeck.get_deck()[i].getSuit() << endl;
}
// Display size of deck
//cout << endl << "The size of deck is: " << mydeck.get_deck().size() << endl;
return 0;
}
任何帮助或智慧之言将不胜感激,我希望我的格式正确...
非常感谢
丹
【问题讨论】:
-
+1 用于发布重现问题的可编译代码,-1 用于不缩小范围。所以 0。
-
你的 Deck 类只不过是一个围绕卡片向量的 [无用] 包装器。在我看来,Deck 类应该有自己的 shuffle 方法,即
void Deck::Shuffle() { random_shuffle(deck.begin(), deck.end()); }- 以及其他方法,例如获取顶牌或底牌,或从牌组中随机获得一张牌。然后我会摆脱你的get_deck()方法。 -
@StarPilot 这是此页面的链接。
-
哈哈。对于那个很抱歉。抓取了错误的窗口 URL。只是其中的一天。
-
@LuchianGrigore 将来我会将代码范围缩小到我的问题所在...谢谢
标签: c++ class vector blackjack