如何在C++中通过引用传递结构?
How to pass struct by reference in C++?
我刚刚开始学习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()
内部的head
和tail
,则必须通过引用传递指针:
void add_student(Student *&, Student *&);
void print_list(Student *&);
当然,您还必须更改您的实现。
相关文章:
- 使用对const结构的const数组的引用进行构造
- 为什么将一个结构的引用设置为等于另一个结构只会更改一个数据成员?
- 如何传递带有通过引用传递的结构参数的函数?
- 具有引用成员的结构是否具有唯一的对象表示形式
- 在结构中使用 switch 引用结构中的数据C++
- 复制引用结构上的赋值
- 取消引用结构以获取第一个成员的值
- 如何引用结构字符串成员
- 引用结构/C++中的变量
- 为什么在取消引用结构后结构成员未初始化
- 引用结构的c++类构造函数
- 引用结构中的另一个结构,其中第二个结构也引用第一个结构
- 结构并集的去引用结构
- 从用户输入中删除引用结构/类成员变量
- 引用结构中的值
- Boost Fusion适应模板化自引用结构的声明
- 引用结构中成员的另一种方法
- C++取消引用结构指针
- 引用结构内部的枚举
- C++引用结构数组