-1

我有一个跟踪人员的任务,现在我需要进行 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”。

4

2 回答 2

1

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

如果这个假设是正确的,那么 for 循环的正确代码是:

for (int i = 0; i < pers.getSize()-1; i++)
于 2015-04-15T09:05:51.110 回答
0

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

于 2012-04-13T10:25:54.093 回答