我试图理解链接列表,但我尝试复制的每个示例都给我一个分段错误。这是我正在制作的示例程序。
struct 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()给我一个段错误
答案 0 :(得分:0)
成员函数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;
}
会员功能显示应声明为
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;
并将其用作上述函数的参数。