我试图理解链接列表,但我试图复制的每个例子都给了我一个分割错误。这是我正在编写的示例程序。
在contacts.hstruct people{
string last;
string first;
int age;
people *next;
};
class Contacts {
private:
people *head;
public:
Contacts() {
head=NULL;
};
void add(string, string, int);
void display();
};
在main.cpp //menu items
//cin >> option
//if option == 1, addContact
//if option == 8, displayContact
//basic in and out here no need to show code
在main.h void addContact() {
Contacts *ptr;
int i, loop=0, a=0;
string l, f;
cout << "number of contacts " << endl;
cin >> loop;
for(i=0; i<loop; i++) {
cout << "enter last name ";
cin >> l;
cout << "enter first name ";
cin >> f;
cout << "enter age ";
cin >> a;
}
ptr->add(l,f,a);
}
void display() {
Contacts *ptr;
ptr->display();
}
在contacts.cpp void Contacts::add(string l, string f, int a) {
people *node = new people;
node->last=l;
node->first=f;
node->age=a;
node->next=NULL;
}
void Contacts::display() {
people *tmp = head;
while(tmp!=NULL) {
cout << tmp->last << endl;
cout << tmp->first << endl;
cout << tmp->age << endl;
tmp->next;
}
的添加函数工作然后display()给出一个段错误
add成员函数应按如下方式定义
void Contacts::add( const string &l, const string &f, int a )
{
head = new people { l, f, a, head };
}
或者如果编译器不支持带有new操作符的初始化列表,则
void Contacts::add( const string &l, const string &f, int a )
{
people *p = new people;
p->last = l;
p->first = f;
p->age = a;
p->next = head;
head = p;
}
成员函数display应该声明为
void Contacts::display() const;
,定义为
void Contacts::display() const
{
for ( people *tmp = head; tmp; tmp = tmp->next )
{
cout << tmp->last << endl;
cout << tmp->first << endl;
cout << tmp->age << endl;
cout << endl;
}
}
其他两个函数应按以下方式定义
void addContact( Contacts &contacts )
{
int n = 0;
cout << "number of contacts " << endl;
cin >> n;
for ( int i = 0; i < n; i++ )
{
string l, f;
int a = 0;
cout << "enter last name ";
cin >> l;
cout << "enter first name ";
cin >> f;
cout << "enter age ";
cin >> a;
contacts.add( l, f, a );
}
}
void display( const Contacts &contacts )
{
contacts.display();
}
在main中定义一个类型为
的对象Contacts contacts;
并将其用作上述函数的参数