【问题标题】:How to pass struct by reference in C++?如何在 C++ 中通过引用传递结构?
【发布时间】:2019-10-17 21:17:32
【问题描述】:

我刚刚开始学习 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++ 初学者,我真的很想从错误中吸取教训。

【问题讨论】:

  • head=temp in add_student 没有任何用处,因为 head 是一个局部变量,是传递的指针的副本
  • 谢谢。我会从下次开始照顾。你能帮我找出我的错误吗?
  • @Jean-FrançoisFabre 哦,好吧。谢谢。我应该改变什么,以便它也改变主函数中的头部。
  • 通过引用传递指针应该可以工作:void add_student(Student *&amp;head, Student *&amp;tail)
  • 为什么print_list 分配了一个new Student 然后立即失去指向它的指针?

标签: c++ list struct


【解决方案1】:

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

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

当然,你也必须改变你的实现。

【讨论】:

  • 非常感谢。您能否告诉我实施部分会发生什么变化,因为我真的在努力解决这部分问题:(很抱歉询问实施。
  • 对不起。没说清楚。您将需要使您的声明与实现的标头部分相匹配。所以说void funcname (...) 的部分,... 部分也必须与声明相匹配。据我所知,其余的实现应该没问题。
  • 是的。我也将实现部分更改为void add_student(Student *&amp;head, Student *&amp;tail)。然而,它抛出了一些错误``` undefined reference to print_list(Student *&amp;) ``` :(
  • 嗯。您能否edit your question 并发布您更改的部分并复制并粘贴您收到的错误?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-12
  • 2011-02-02
  • 1970-01-01
  • 1970-01-01
  • 2014-12-13
相关资源
最近更新 更多