我创建了一个项目,其中包含一个名为 Card 的类,该类具有名称、花色和值(value)。
我有一个牌组类,它生成一个包含 52 个元素的 vector 。
我有一个处理许多 vector 的表类:弃牌堆、玩家手等。
然后只有我的主 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;
甲板.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;
表格.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
}
这就是问题所在,我在程序中放置了一些 cout,这就是正在发生的事情。请注意它在交易方法中如何完美地工作,但一旦它返回到我的主要 cpp,它就会忘记所有关于移动该卡的事情。然而,主牌组有 51 张牌,这意味着它起作用了,这是有道理的,因为变量牌组没有传入。
如果你们能提供任何帮助,我将不胜感激。
最佳答案
问题是 theTable.getPlayersCards()
正在返回 vector<Card> playersCards
的拷贝而不是对其的引用。
尝试在 Table.cpp
中更改它:
vector<Card>& Table::getPlayersCards()
{
return playersCards;
}
vector<Card>& Table::getDiscardPile()
{
return discard;
}
这在 Table.h
中:
vector<Card>& getPlayersCards();
vector<Card>& getDiscardPile();
关于C++ 通过引用传入 Vector 但更改仍未保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31844086/