【发布时间】:2009-10-12 03:04:18
【问题描述】:
在我的代码中,我有一个 Student 对象的向量。
vector<Student> m_students;
我想:
- 检查向量是否包含任何具有特定名称的学生。
- 如果不存在这样的学生,请添加一个新学生。
- 向同名的学生添加数据。
考虑以下代码:
// Check to see if the Student already exists.
Student* targetStudent = NULL;
for each (Student student in m_students)
{
if (student.Name() == strName)
{
targetStudent = &student;
break;
}
}
// If the Student didn't exist, add it.
if (targetStudent == NULL)
{
targetStudent = new Student(strName);
m_students.push_back(*targetStudent);
}
// Add the course info to the Student.
targetStudent->Add(strQuarter, strCourse, strCredits, strGrade);
当我调用 m_students.push_back(*targetStudent); 时,似乎向量“m_students”最终得到了“targetStudent”当时指向的 Student 对象的副本。
随后尝试添加到 targetStudent 并不会更改向量中包含的对象。
如何从指向对象的指针开始,将该对象添加到向量中,然后访问向量中的对象?
【问题讨论】: