如何在C++中通过引用传递结构?

How to pass struct by reference in C++?

本文关键字:引用 结构 C++      更新时间:2023-10-16

我刚刚开始学习C++。

我正在尝试在不使用类的情况下创建一个链表。所以,在主函数中,我有头和尾指针。之后,我要求用户执行任务。如果用户想要添加新学生,则必须输入 A。要打印列表,用户必须输入 P 并退出程序。我编写了以下程序来完成任务:

#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
struct Student {
string name;
Student* next;
};
void add_student(Student *, Student *);
void print_list(Student *);
int main()
{   
Student *head, *tail;
head=NULL;
tail=NULL;
while (true) {
cout << "nOptions:n";
cout << "To add Student [A]n";
cout << "To print Student list [P]n";
cout << "Quit Q  [Q]n";
string choice = "";
cin >> choice;
if (choice.compare("A") == 0) {
add_student(head, tail);
cout << "Book successfully added.n";
}
else if (choice.compare("P") == 0) {
print_list(head);
}
else if (choice.compare("Q") == 0) {
cout << "Bye!";
break;
}
else {
cout << "Invalid choice.n";
}
}
}
void add_student(Student *head, Student *tail)
{
string name;
cout << "Enter name of student n";
cin >> name;
Student *temp = new Student;
temp->name = name;
temp->next = NULL;
if(head==NULL)
{
head=temp;
tail=temp;
temp=NULL;
}
else
{   
tail->next=temp;
tail=temp;
}
// Check student has been added successfully.
print_list(head);
}
void print_list(Student *head)
{
cout << "Student list is as following:n";
Student *temp=new Student;
temp=head;
while(temp!=NULL)
{
cout<< temp->name <<"n";
temp = temp->next;
}
}

但是,问题是每次添加新学生时,它都会作为列表中的第一个元素添加,而不是将其添加到最后一个元素。我想,我在引用传递方面犯了一些错误。

请您检查并建议我在哪里犯了错误。这将有很大的帮助,因为我是C++的初学者,我真的很想从错误中吸取教训。

如果要修改main()内部的headtail,则必须通过引用传递指针:

void add_student(Student *&, Student *&);
void print_list(Student *&);

当然,您还必须更改您的实现。