【问题标题】:C++ Passing in Vector by Reference but changes still not being savedC ++通过引用传递向量,但更改仍未保存
【发布时间】: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,但是右值对非恒定引用是什么意思?还有你所说的警告级别是什么意思?

标签: c++ vector


【解决方案1】:

问题在于theTable.getPlayersCards() 正在返回vector&lt;Card&gt; playersCards 的副本,而不是对它的引用。

尝试在Table.cpp 中更改此设置:

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

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

这个在Table.h:

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

【讨论】:

  • 做到了。现在完美运行。非常感谢你们。我不知道返回值是这样工作的。
  • @Hatefiend 你应该问问你的导师为什么他没有向你解释这个基本概念。
  • @JonathanPotter 我的大学课程还很早。到目前为止,我只完成了两个。最近的一堂课是“C 入门”,我们停在“指针”上。我知道答案将是“阅读教科书”,但老实说,我在谷歌上搜索和搜索,找不到任何关于此的内容。
【解决方案2】:

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

【讨论】:

  • 非常感谢。不知道。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-05
  • 1970-01-01
  • 1970-01-01
  • 2012-08-31
相关资源
最近更新 更多