简体   繁体   English

C ++通过引用传递矢量,但更改仍未保存

[英]C++ Passing in Vector by Reference but changes still not being saved

I made a project with a class called Card which has a name, suit, and value. 我制作了一个名为Card的类的项目,该类具有名称,西装和值。

I have a deck class which makes a vector of which has 52 elements. 我有一个甲板类,使它的向量包含52个元素。

I have a table class which handles many vectors: discard pile, players hand, etc. 我有一个处理许多向量的表格类:弃牌,玩家手牌等。

Then just my main cpp which runs it all. 然后就是我的主cpp,可以运行所有内容。

Deck.h 加入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 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 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 Table.cpp

vector<Card> Table::getPlayersCards()
{
    return playersCards;
}

vector<Card> Table::getDiscardPile()
{
    return discard;
}

Main.cpp Main.cpp的

//VARIABLES
Deck theDeck;
Table theTable;

int main()
{
    theDeck.deal(theTable.getPlayersCards()); //Attempt to deal a card
    //out to the player's hand
}

so here's the problem, I put some couts in the program and here's what is happening. 所以这就是问题所在,我在程序中添加了一些提示,这就是正在发生的事情。 Notice how it works perfectly once it's in the deal method but as soon as it goes back to my main cpp, it forgets all about ever having moved that card. 请注意,一旦进入交易方法,它会如何完美工作,但是一旦回到我的主要cpp,它就会忘记所有曾经移动过该卡的情况。 However the main deck has 51 cards, meaning THAT worked, which makes sense because the variable deck was not passed in. 但是,主甲板有51张牌,这意味着THAT起作用了,这是有道理的,因为未传递可变甲板。

在此处输入图片说明

If you guys can offer any help, I would be so appreciative. 如果你们能提供任何帮助,我将非常感激。

The problem is that theTable.getPlayersCards() is returning a copy of vector<Card> playersCards instead of a reference to it. 问题在于theTable.getPlayersCards()返回的是vector<Card> playersCards的副本,而不是对其的引用。

Try changing this in Table.cpp : 尝试在Table.cpp中进行Table.cpp

vector<Card>& Table::getPlayersCards()
{
  return playersCards;
}

vector<Card>& Table::getDiscardPile()
{
  return discard;
}

and this in Table.h : 这在Table.h

vector<Card>& getPlayersCards();
vector<Card>& getDiscardPile();

The result from getPlayersCards() is a copy of the cards. getPlayersCards()的结果是纸牌的副本。 Not a reference. 没有参考。 So when deal returns the copy of its argument gets destroyed. 因此,当deal返回时,其参数的副本将被销毁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM