【发布时间】:2015-08-05 22:47:42
【问题描述】:
我用一个名为 Card 的类创建了一个项目,该类具有名称、花色和值。
我有一个甲板类,它制作了一个包含 52 个元素的向量。
我有一个处理许多向量的表格类:弃牌堆、玩家手牌等。
然后只是我的主 cpp 运行它。
Deck.h
public:
Deck();
void deal(vector<Card>& pile); //Deals a card from the top
//of the deck to any passed-in hand or pile.
private:
vector<Card> deck;
Deck.cpp
void Deck::deal(vector<Card>& pile) //Deal a card to whichever pile on the table.
{
pile.push_back(deck[deck.size() - 1]); //Add the card from the deck to the pile
deck.pop_back(); //Remove the card that we copied from
}
Table.h
public:
Table();
void deal(vector<Card>& pile); //Deals a card from the top
//of the deck to any passed-in hand or pile.
vector<Card> getPlayersCards();
private:
vector<Card> playersCards;
vector<Card> discard;
Table.cpp
vector<Card> Table::getPlayersCards()
{
return playersCards;
}
vector<Card> Table::getDiscardPile()
{
return discard;
}
Main.cpp
//VARIABLES
Deck theDeck;
Table theTable;
int main()
{
theDeck.deal(theTable.getPlayersCards()); //Attempt to deal a card
//out to the player's hand
}
所以这就是问题所在,我在程序中添加了一些 couts,这就是正在发生的事情。请注意,一旦它在 deal 方法中,它是如何完美地工作的,但是一旦它回到我的主 cpp,它就会忘记所有关于曾经移动过那张卡的事情。然而,主牌组有 51 张牌,这意味着它起作用了,这是有道理的,因为没有传入可变牌组。
如果你们能提供任何帮助,我将不胜感激。
【问题讨论】:
-
可能与
getPlayersCards()/getDiscardPile()按值返回vectors 有关,但如果没有完整的示例,很难确定。您的代码甚至无效,因为您将右值绑定到非常量引用。我猜你是用 VisualStudio 编译的?调高警告级别。 -
theTable.getPlayersCards()是临时的,所以theDeck.deal(theTable.getPlayersCards())甚至不应该编译... -
你可以写
deck.back()而不是deck[deck.size() - 1]。在执行此操作之前,您应该确保deck.empty()为 false。 -
@Praetorian 我确实使用Visual Studio,但是右值对非恒定引用是什么意思?还有你所说的警告级别是什么意思?