题目描述
我的代码在运行一部分后会意外终止,我知道是内存出现了问题,但到底是哪句话出了错?
这是我们学校的一道练习实验题
相关代码
#ifndef ADDRESS_BOOK_H
#define ADDRESS_BOOK_H
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::string;
struct address
{
string name;
long long phone_number;
long long classroom;
long long dormitory;
};
class book
{
protected:
address* a = NULL;
int listsize;
int arraylength;
public:
book();
book(const book& a);//复制构造函数;
~book();
void insert(book &a);
void _delete(book& a,string c);
void compile(book& a,string c);
bool find(const book& a,string c);
void print(const book& a,int n);
};
#endif
book::book()
{
listsize = 0;
arraylength = 50;
a = new address[arraylength];
for (int i = 0; i < arraylength;i++)
{
a[i].classroom = 0; a[i].dormitory = 0; a[i].phone_number = 0;
}
}
book::book(const book& c)
{
arraylength = c.arraylength;
listsize = c.listsize;
a = new address[arraylength];
for (int i = 0; i < arraylength; i++)
{
a[i].name = c.a[i].name;
a[i].classroom = c.a[i].classroom;
a[i].dormitory = c.a[i].dormitory;
a[i].phone_number = c.a[i].phone_number;
}
}
void book::insert(book &b)
{
if (b.listsize == b.arraylength)
{
delete []b.a;
b.a = new address[2*arraylength];
for (int i = b.arraylength; i < 2*b.arraylength; i++)
{
b.a[i].classroom = 0; b.a[i].dormitory = 0; b.a[i].phone_number = 0;
}
b.arraylength = b.arraylength * 2;
}
cin >> b.a[listsize].name >> b.a[listsize].phone_number >> b.a[listsize].classroom >> b.a[listsize].dormitory;
listsize++;
}
void book::_delete(book &b,string c)
{
for (int i = 0; i < listsize; i++)
{
if (b.a[i].name == c)
{
for (i=i; i < b.listsize; i++)
{
b.a[i].classroom = b.a[i+1].classroom;
b.a[i].dormitory = b.a[i+1].dormitory;
b.a[i].phone_number = b.a[i+1].phone_number;
b.a[i].name = b.a[i+1].name;
}
a[listsize].classroom = 0; a[listsize].dormitory = 0; a[listsize].phone_number = 0;
break;
}
}
}
void book::compile(book& b,string c)
{
int n;
for (int i = 0; i < b.listsize; i++)
{
if (b.a[i].name == c)
{
cin >> n;
if (n == 1)
{
long long n1;
cin >> n1;
b.a[i].phone_number = n1;
}
else if (n == 2)
{
int n2;
cin >> n2;
b.a[i].classroom = n2;
}
else if (n == 3)
{
int n3;
cin >> n3;
b.a[i].dormitory = n3;
}
}
}
}
bool book::find(const book& b,string c)
{
int i;
for (i = 0; i < b.listsize; i++)
{
if (b.a[i].name == c)
return true;
}
return false;
}
void book::print(const book& b,int n)
{
long long sum = 0;
for (int i = 0; i < b.listsize&&b.a[i].classroom == n; i++)
sum = sum ^ b.a[i].dormitory;
cout << sum <<endl;
}
book::~book()
{
for (int i = 0; i < arraylength; i++)
{
delete []a;
}
}
int main()
{
int k=0,nn1;
int nn2;
cin >> nn1;
book b;string c;
for(int i = 0;i<nn1;i++)
{
cin>>nn2;
if (nn2 == 0)
b.insert(b);
else if (nn2 == 1)
{
cin >> c;
b._delete(b, c);
}
else if (nn2 == 2)
{
cin >> c;
b.compile(b, c);
}
else if (nn2 == 3)
{
cout << b.find(b, c) << endl;
}
else if (nn2 == 4)
{
int nnn; cin >> nnn;
b.print(b,nnn);
}
}
return 0;
}
麻烦大佬我到底是哪里的错误,谢谢!
析构函数有问题
不能循环执行,执行完第一次,a的地址已经无效了。
改成