【发布时间】:2013-12-24 23:09:27
【问题描述】:
我正在使用列表迭代器将 Pets 的所有年龄设置为 1,但更改不会在 for 循环之外持续存在:
#include <iostream>
#include <stdio.h>
#include <list>
using namespace std;
class Pet{
public:
int age;
};
class Person{
public:
list<Pet> pets;
};
int main(int argc, char **argv) {
Person bob;
Pet p1;
p1.age = 0;
bob.pets.push_back(p1);
cout << "Start with: "<<p1.age << endl;
std::list<Pet>::iterator itPet;
for (itPet = bob.pets.begin(); itPet != bob.pets.end(); ++itPet) {
Pet p = (*itPet);
p.age = 1;
cout << "Right after setting to 1: "<<p.age << endl;
}
cout << "After the for loop: "<<p1.age << endl;
return 0;
}
输出:
Start with: 0
Right after setting to 1: 1
After the for loop: 0
为什么 p1 没有更新?如果不是 p1,又更新了什么?
谢谢!
【问题讨论】: