我有两个派生类(Court和Machine)的抽象类(Service)。我还有一个服务指针数组,我试图从包含Court和Machine信息的文本文件中读取。为了确定哪个类别的信息,我使用if
。
我的代码编译,但在执行时我收到分段错误。我知道这意味着我访问内存不应该,但我不确定我做错了什么。
我从未使用指针数组。在尝试输入对象时,我是否做错了什么?我确保在课程开始时包括这两个课程。
Service *listServices[20];
ifstream ArchService;
ArchService.open("Services.txt");
while(!ArchService.eof())
{
for (int iA = 0; iA < 20; iA++)
{
string clave, descripcion, deporte;
int tiempomax, maxpersonas;
char tipo;
double costo;
bool instructor;
ArchService >> clave >> tiempomax >> tipo >> costo;
if (tipo == 'C' || tipo == 'E' || tipo == 'B')
{
ArchService >> instructor;
ArchService.ignore();
getline(ArchService, descripcion);
listServices[iA] = new Machine(clave, tiempomax, tipo, costo, instructor, descripcion);
}
else
{
ArchService >> maxpersonas;
ArchService.ignore();
getline(ArchService, deporte);
listServices[iA] = new Court(clave, tiempomax, tipo, costo, maxpersonas, deporte);
}
listServices[iA]->print();
}
ArchService.close();
}
答案 0 :(得分:0)
listServices
的每个元素都是一次又一次地分配,旧值不是delete
d,所以它们只是保持悬空引用并形成多个内存泄漏。可能这是根本原因。如前所述,如果你想要的只是填充20个列表服务的数组,你宁可删除while(!ArchService.eof())
循环。