分段错误和吸气器问题

Segmentation fault and getter issue

本文关键字:问题 错误 分段      更新时间:2023-10-16

我有一个跟踪人员的任务,现在我需要进行 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();>getName() 中它说"重复的数字 0 无效"。

虽然您没有显示足够的代码来完全理解问题,假设 pers 是标准库中的某种形式的容器,但大多数大小函数给出从 1 开始计数的元素数量大小的结果,而容器的元素访问从零开始。这意味着要正确访问所有元素,您需要从容器的大小中减去一个。

如果此假设为真,则 for 循环的正确代码为:

for (int i = 0; i < pers.getSize()-1; i++)

您显示的代码不足以找出导致 seg. 错误的原因。 我的猜测是你过度索引到elems容器中(也许pers.getSize()返回了错误的值?