[英]How to pass struct by reference in C++?
我剛開始學習C++。
我正在嘗試在不使用 class 的情況下創建鏈接列表。 所以,在主function中,我有頭尾指針。 之后,我要求用戶執行任務。 如果他想添加一個新學生,用戶必須輸入 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 *&);
當然,你也必須改變你的實現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.