分段错误和吸气器问题
Segmentation fault and getter issue
我有一个跟踪人员的任务,现在我需要进行 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()
返回了错误的值?
相关文章:
- 警告处理为错误这里有什么问题
- Project Euler问题4的错误解决方案
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 谷歌启动B轮巴士路线问题错误的答案?
- C++编译问题错误 - C2332:<类:缺少标记名称>
- 编译方面的问题.错误E0413、E0434、C2664、C2440
- 在C 中的初学者,我面临此问题错误C3867
- C++:创建线程时出现问题;错误 C2672:"std::invoke":找不到匹配的重载函数
- 模板方法定义的问题 - 错误C2244:无法将函数定义与现有声明匹配
- C 继承问题错误C2084功能已经具有主体
- 安装 QT 后的新手问题 - 错误:未知类型名称"QApplication"
- Stroustrup的代码审查-编程原理-Ch-4-问题:3-错误:矢量下标超出范围
- C 问题错误在此函数中被统一使用
- 返回模板类的模板函数 - GCC 编译问题 - 错误:令牌之前'<'预期非限定 ID
- CMake CLion 问题 - 错误:无法确定目标"XYZ"的链接语言
- 试图将数据写入文件时出现问题.错误LNK2019:未解析的外部符号
- c++初始化列表问题-错误:试图引用已删除的函数
- visual studio 2012 - SFGUI/ c++编译问题.错误2019:未解析的外部符号
- Makefile问题:错误127,255,在Makefile中运行程序
- 将成员函数用作操作数时出现C++问题.错误C2679