我有一个跟踪人员的任务,现在我需要进行 crud 操作。当我尝试访问动态数组时,人员 id 的 getter 工作,但人员电话的 getter 返回“分段错误”,而人员姓名的 getter 什么也没显示。
//the main.cpp test that gives the following error
Controller ctrl(repp,repa,valp,vala);
ctrl.addPerson(1,"Name","0744000000","Adress");
ctrl.show();
//controller show method, repp - instance of repository in controler
void Controller::show()
{
repp->show();
}
//repository show method, which doesn't work
void PersonInMemoryRepository::show()
{
for(int i=0; i < pers.getSize(); i++)
cout<<pers.get(i)->getName()<<endl;
}
//getById method in repository
const Person* PersonInMemoryRepository::getById(int id)
{
for (int i = 0; i < pers.getSize(); i++)
{
if (pers.get(i)->getId() == id) {
return pers.get(i);
}
}
return NULL;
}
//the Person class
class Person
{
public:
Person(int i, string n, string p, string a);
const string& getName() const {
return name;
}
const string& getPhone() const {
return phone;
}
const string& getAdress() const {
return adress;
}
int getId() const {
return id;
}
~Person();
private:
int id;
string name;
string phone;
string adress;
};
//pers.get(i)
template<typename Element>
Element DynamicArray<Element>::get(int poz) {
return elems[poz];
}
提前致谢。
更新:当它上线时 cout<getName(); . pers.get(i) 效果很好,它是 Person* 类型向量,当我在调试器中取消引用它时,它具有正确的值,但在 ->getName() 处显示“无效的重复次数 0”。