【发布时间】:2011-03-10 14:15:41
【问题描述】:
我已经关注了很长时间,但这是我第一次提出问题。简而言之,问题是; vector<Student*> studentvector 是一个对象指针向量,似乎将学生信息推回为 student ;但是当我打印以查看向量中的第一个是否按预期执行时,我看到它总是用新来的学生信息更新第一条记录,尽管studentvector.size() 没有问题它将记录推回向量我打了多少次addStudent(...) 但它用最后一个学生的信息填充了所有向量。在不使用智能指针或高级东西的情况下,如何在此框架内成功地用正确的信息填充向量?
对不起,如果我对我的问题含糊不清。您可以引导我提供理解问题所必需的内容。提前致谢。
addStudent(const string alias, const string name) throw(StudentException)
{
Student* student = new Student(alias, name)
studentvector.push_back(student);
cout << studentvector.front() << endl;
}
那是Student的实现;
#include "Student.h"
string *Alias;
string *Name;
Student::Student(string alias)
{
Alias = new string(alias);
}
Student::Student(string alias, string name)
{
Alias = new string(alias);
Name = new string(name);
}
Student::~Student()
{
delete Alias;
delete Name;
}
const string& Student::getAlias() const
{
return *Alias;
}
void Student::setAlias(const string& alias)
{
*Alias = alias;
}
const string& Student::getName() const
{
return *Name;
}
void Student::setName(const string& name)
{
*Name = name;
}
考虑别名未保留。
【问题讨论】:
-
您能否添加一个示例来说明您如何访问 studentvector?
-
1) 不要使用异常规范 2) 学习使用调试器
-
我确信您在上面编写的代码是正确的,并且不会导致您描述的问题。然而,还有许多其他地方可以,比如
Student类,operator<<(std::ostream&, const Student *)(或者你真的只打印地址,因为上面的代码在没有该运算符的情况下),声明studentvector的方式和我可能忘记了一些。您需要提供更多背景信息才能获得更多诊断信息。 -
(给未来的读者注意:这里的许多答案和 cmets 都是在 afu 提供实现 Student 的代码之前编写的,这正是问题所在。这就是为什么他们未能解决实际问题问题。)
-
@Gareth McCaughan 感谢您的澄清:)
标签: c++ pointers object vector