【问题标题】:c++ Dereferecing Pointers assigned by pass-by-reference giving random valuesc ++ Dereferecing Pointers通过传递引用分配给随机值
【发布时间】:2017-06-20 05:18:35
【问题描述】:

我有一个指针数组,它们应该保存其他对象的内存位置。将数组添加到 list2 并从该 Object 打印出一个值给了我正确的值。但是尝试从另一个函数打印它会给我随机值。

类:

class Airline() {
Airline();
Flight *list2[20]; //array of pointers to Flight
};

class Flight() {
int flightNo;
int MaxPeople;
};

添加飞行功能:

currentPos1 =-1     //Global Variable

void Airline::addFlight(Flight flight) {
currentPos1++;
list2[currentPos1] = &flight;
cout <<(*list2[currentPos1]).flightNo <<"\n"; //Gives proper Value
}

ShowAllFlights 函数:

void AirDB::showAllFlights() {
  for (int i = 0; i <= currentPos1; i++)
    {
     //Both cout's provide random values;
      cout <<"\nFlight Number: " <<list2[i]->flightNo;
      cout <<"\nMaxPeople: " << list2[i]->maxPeople;
     }
}

我的引用和取消引用在这里有错吗? 任何帮助将不胜感激。

【问题讨论】:

  • 评论//array of pointers to pointers 应为array of pointers to Flight。航班不是指针。

标签: c++ pointers multidimensional-array pass-by-reference


【解决方案1】:

这里有一个问题:

list2[currentPos1] = &amp;flight;

这不起作用,因为您正在分配一个指向临时Flight 的指针。当addFlight 函数返回时,该指针不再有效。

您要做的是通过引用传递Flight(最好是const 引用):

void Airline::addFlight(const Flight& flight)

请注意,这取决于您发送给addFlight 的参数的生命周期。对于这个特定的函数,flight 将是有效的,但在函数调用之后,您发送的参数也必须在您打算使用存储在 list2 中的指针的生命周期内有效。

使用std::vector&lt;Flight&gt; 代替指向Flight 的指针数组会更简单。

【讨论】:

  • 这可能无法解决问题,因为调用参数可能很快就会结束其生命周期
  • 谢谢。这正是我所缺少的。
猜你喜欢
  • 2020-12-06
  • 2020-12-07
  • 2010-12-22
  • 2020-04-01
  • 1970-01-01
  • 2020-05-03
  • 1970-01-01
  • 2017-08-12
  • 1970-01-01
相关资源
最近更新 更多