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

标签 c++ vector

我创建了一个项目,其中包含一个名为 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 张牌,这意味着它起作用了,这是有道理的,因为变量牌组没有传入。

enter image description here

如果你们能提供任何帮助,我将不胜感激。

最佳答案

问题是 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/

相关文章:

c++ - 派生类中的运算符==永远不会被调用

c++ - 矩阵模板库矩阵求逆

c++ - 通过指针将 char 数组传输到另一个临时数组指针

删除向量的孤立元素

c++ - 在我提供的这个示例中,如何将二维 std::vector 的逻辑更改为 vector[row] [col] 而不是 vector[col] [row] ?

c++ - 创建临时 vector

c++ - 默认构造函数被误解为函数名称

c++ - 我究竟如何使用函数 push_back 和 pop_back()?我在下面的链接中查找了它们,但仍然不明白

c++ - 带有 std::vector 的 VBO

c++ - 防止在复制构造函数中切片