C ++通过引用传递Vector但仍未保存更改

时间:2015-08-05 22:47:42

标签: c++ vector

我创建了一个名为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,这就是正在发生的事情。注意一旦它在交易方法中它是如何工作的,但是一旦它回到我的主要cpp,它就会忘记所有关于移动该卡的事情。然而,主甲板上有51张牌,这意味着它有效,这是有道理的,因为可变甲板没有传入。

enter image description here

如果你们能提供任何帮助,我会非常感激。

2 个答案:

答案 0 :(得分:3)

问题是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();

答案 1 :(得分:1)

getPlayersCards()的结果是卡片的副本。不是参考。因此,当deal返回时,其参数的副本将被销毁。

相关问题