【发布时间】: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