C++ c++;调用显示函数时的LinkedList
我试图理解链接列表,但我试图复制的每个示例都会给我一个分段错误。这是我正在编写的示例程序 在contacts.h中C++ c++;调用显示函数时的LinkedList,c++,linked-list,segmentation-fault,C++,Linked List,Segmentation Fault,我试图理解链接列表,但我试图复制的每个示例都会给我一个分段错误。这是我正在编写的示例程序 在contacts.h中 struct people{ string last; string first; int age; people *next; }; class Contacts { private: people *head; public: Contacts() { head=NULL; }; void add(string, string, in
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();
};
in main.cpp
//menu items
//cin >> option
//if option == 1, addContact
//if option == 8, displayContact
//basic in and out here no need to show code
大体上
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();
}
void addContact(){
联系人*ptr;
int i,loop=0,a=0;
字符串l,f;
库特环;
对于(i=0;i l;
cout>f;
cout>a;
}
ptr->添加(l、f、a);
}
无效显示(){
联系人*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;
}
void Contacts::add(字符串l、字符串f、int a){
人员*节点=新人员;
节点->最后一个=l;
节点->第一个=f;
节点->年龄=a;
节点->下一步=空;
}
void Contacts::display(){
人*tmp=头;
while(tmp!=NULL){
cout last成员函数add应按以下方式定义
void Contacts::add( const string &l, const string &f, int a )
{
head = new people { l, f, a, head };
}
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();
}
或者,如果编译器不支持带有新运算符的初始值设定项列表,则
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;
}
}
你可能希望:while(head!=NULL)
变成:while(tmp!=NULL)
。考虑到该循环中没有任何内容会修改head
,你会在那里呆一段时间(至少直到崩溃为止)。这并不重要。ptr->add(l,f,a)
早在那之前就调用了未定义的行为。web上有成千上万个链表的功能示例。也许可以回顾一下。代码中有多个错误。您应该首先尝试从struct people中构建一个简单的链表。只有在实现了这一点之后,才能将其与Contact类相结合您的错误原因似乎是,当您执行while条件时,head没有指向任何东西(甚至不为NULL,因为您是从未初始化的指针调用它)。非常感谢。这帮助了很多。我喜欢像您这样的人,他们在不批评我们新手的情况下提供帮助。这些人可以从您那里学到很多。再次感谢您!
Contacts contacts;