C++初学者,for循环中可更新对象的向量,如何更新和保留它们的属性

问题描述 投票:0回答:1

我是 C++ 新手,试图找出原因以及如何解决以下问题。 如何让 s->getNum() 在 for 循环之后根据循环中 setNum 设置的值显示值 (6)? 谢谢您的协助。

Student* s = new Student();
Student* t = new Student();

vecList.push_back(*s);
vecList.push_back(*t);

int i = 1;
for (Student& it : vecList) {
    i++;
    it.setNum(2 * (i + 1));
    it.print();  //prints the correct values 6 and 8 for each student respectively
    //it.getNum();  returns 6 as expected
}
float x = s->getNum(); //returns 0, not the 6 expected from Student.
s->print();  //prints 0, ie the orginal Student at construction of the object, not the modified value at it.setNum in the for loop.

我尝试了很多组合、参考指针等,但我认为我缺少一个基本概念。

c++ loops scope reference settings
1个回答
0
投票
vecList.push_back(*s);

这是复制 *s,然后将副本推回 vecList,而不是将 *s 本身推回到 vecList。

因此您对 vecList 中的元素所做的操作不会影响 *s 或 *t。

© www.soinside.com 2019 - 2024. All rights reserved.