异质链表程序
#include "iostream.h"#include "string.h"
#include "stdlib.h"
#include "iomanip.h"
class COLLIGEPERSON{ //大学人员
// char name[10];
int age; //年龄
char secritynum[15];
public:
char name[10]; //姓名
COLLIGEPERSON(char *,int,char *);
~COLLIGEPERSON();
virtual void print()const;
};
COLLIGEPERSON :: COLLIGEPERSON(char * n, int ag, char *s)
{
strcpy(name,n);
age=ag;
strcpy(secritynum,s);
}
COLLIGEPERSON::~COLLIGEPERSON()
{
if(name) free(name);
if(secritynum) free(secritynum);
}
void COLLIGEPERSON:: print()const //输出信息
{
cout<<setw(10)<<"name"<<setw(10)<<name<<endl;
cout<<setw(10)<<"age"<<setw(10)<<age<<endl;
cout<<setw(10)<<"secritynum"<<setw(10)<<secritynum<<endl;
}
class STUDENT:public COLLIGEPERSON{ //大学学生,由大学人员派生
int grade;
double score; //新成员,年龄和分数
public:
STUDENT(char *n, int ag, char *s,int gr, double sc);
void print()const;
};
STUDENT::STUDENT(char *n,int ag, char *s, int gr, double sc):COLLIGEPERSON(n,ag,s)
{
grade=gr;
score=sc;
// cout<<"mmmm";
}
void STUDENT::print()const
{
cout<<"\n\n\t\tstudent\n\n";
COLLIGEPERSON::print();
cout<<setw(10)<<"grade:"<<setw(10)<<grade<<endl;
cout<<setw(10)<<"score:"<<setw(10)<<score<<endl;
// COLLIGEPERSON::print();
}
class COLLIGE{ //管理大学人员的链表
struct coll{
COLLIGEPERSON *person;
coll *next;
coll(COLLIGEPERSON *per, coll *n){
person=per;
next=n;
}
~coll(){ if(person) delete person; }
}*head; //每个结点的内容
public:
int add(COLLIGEPERSON *cc){ head=new coll(cc,head); return 1;} //插入
int remove(char *cc); //删除
COLLIGE(){ head=0; }
~COLLIGE();
void print();
};
int COLLIGE:: remove(char *cc)
{
coll *p, *q;
p=q=head;
cout<<"mm"<<endl;
while(p!=0&&strcmp(p->person->name,cc)){
q=p;
p=p->next;
}
if(!p) cout<<"the name does not exits"<<endl;
if(q==p) head=p->next;
else q->next=p->next;
delete p; //?????????????
return 1;
}
COLLIGE::~COLLIGE(){
coll *p=head;
while(head)
{
p=p->next;
delete head;
head=p;
}
}
void COLLIGE::print()
{
coll *p=head;
while(p){
p->person->print();
p=p->next;
}
}
void main()
{
COLLIGE collige;
collige.add(new STUDENT("luyi",21,"123",2,90));
collige.add(new STUDENT("dd",22,"12",5,50));
collige.print();
collige.remove("dd");
cout<<"bb"<<endl;
collige.print();
}
程序结构其实很简单,设了个虚基类,还有派生类没必要发上来。很奇怪打问号的地方用delete结果会输出有问题,用free则ok,但是用free的话不是会造成内存泄漏吗?
还有程序运行时会有debug library 弹出,说会造成assertion failure,在VC和STDIO 2005均是如此,当然点终止的话结果还是会出来,没什么影响,但why,是出了什么问题啊?
有没有哪位大虾帮着解决下啊