【问题标题】:Reference not returning? [closed]参考不返回? [关闭]
【发布时间】:2018-02-23 21:46:02
【问题描述】:

我的班级有一个对象数组,称之为Foo。它在类中存储为Foo* m_Foos。假设它的值是 [0],保证,并且 Foo 有一个名为 IsSet 的属性,这只是一个布尔值。

void TryThis()
{
   Foo returnValue;
   GetValue(returnValue);
   returnValue.IsSet = true;
   if(m_Foo[0].IsSet != returnValue.IsSet)
   {
      // ERROR!!!!
   }
}

void GetValue(Foo &container)
{
   container = m_Foos[0];
}

谁能解释为什么 m_Foo[0] =/= returnValue?我的语法错误在哪里?

我希望 m_Foo[0] 与 returnValue 的引用相同,内存中的 Foo 相同。

【问题讨论】:

  • GetValue()returnValue 的值分配为等于m_Foos[0] 的值。它不会导致 returnValue 成为对 m_Foos[0] 的引用。
  • 我更新了问题以提供示例。代码现在有条件
  • 不确定您还想如何改写它。我得到了答案,所以没关系。

标签: c++ pass-by-reference


【解决方案1】:

TryThis() 没有修改存储在m_Foos 数组中的Foo 对象。

GetValue()Foo 对象从m_Foos[0] 分配给另一个Foo 对象,该对象是TryThis() 的本地对象。在该分配期间正在制作副本TryThis() 正在修改副本,而不是原件。

如果你想让TryThis() 直接修改原来的Foo 对象,你需要做更多这样的事情:

void TryThis()
{
   Foo &returnValue = GetValue();
   returnValue.IsSet = true;
   // m_Foo[0] is set true.
}

Foo& GetValue()
{
   return m_Foos[0];
}

或者这个:

void TryThis()
{
   Foo *returnValue;
   GetValue(returnValue);
   returnValue->IsSet = true;
   // m_Foo[0] is set true.
}

void GetValue(Foo* &container)
{
   container = &m_Foos[0];
}

【讨论】:

  • 啊,所以我需要一个指向 TryThis 的指针,我不能让它成为本地的吗?谢谢。
  • @user99999991,这不是一个指针。这是一个参考。
  • 我的意思是第二个例子,它有一个指针。更符合我原始示例的格式,带有 void 函数。我的错。
  • TryThis() 需要使用指向m_Foos[0] 的引用/指针,而不是它的副本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-15
  • 2017-10-05
相关资源
最近更新 更多