只是这里的初学者。
我正在尝试将一些对象存储在向量中,以便稍后循环它,但是之后引用发生了变化,我不确定发生了什么
代码如下;
#include <iostream>
#include <vector>
using namespace std;
class Car;
class Garage {
public:
vector<Car*> vCar;
};
class Car {
public:
short id;
};
int main()
{
Garage garage;
short i;
for(i = 0; i < 10; i++) {
Car car;
car.id = i;
garage.vCar.push_back(&car);
}
for(i = 0; i < garage.vCar.size(); i++) {
cout << i << " " << garage.vCar[i]->id << endl;
// output 9,9,9,..9 instead of 1,2,3,4...10, why is that?
}
return 0;
}