gpt4 book ai didi

c++ - 使用类时如何使用链表

转载 作者:行者123 更新时间:2023-12-03 07:11:55 24 4
gpt4 key购买 nike

因此,我有一个名为的类(class)学生,我必须使用链接列表列出学生列表。
下面有我的代码:

#include <string>
#include <iostream>
using std::string;
using std::cout;
using std::endl;

class Student
{
private:
int grade;
string name;
public:
Student(int grade, string name)
{
this->grade = grade;
this->name = name;
}
void getStudent()
{
cout << name << grade << endl;
}

};

class Node {
public:
Student student;
Node* next;
};

void printList(Node* n)
{
while (n != NULL)
{
n->student.getStudent();
n = n->next;
}
}

int main()
{
Node* studentList = NULL;

studentList = new Node(); // Reported error at this line
studentList->student = Student(1, "Matei");
printList(studentList);

}
但是我收到一个错误:无法引用“节点”的默认构造函数-它是一个已删除的函数。
请帮我!

最佳答案

当我们compile your code(GodBolt.org)时,我们得到:

<source>:44:28: error: use of deleted function 'Node::Node()'
44 | studentList = new Node(); // Reported error at this line
| ^
<source>:25:7: note: 'Node::Node()' is implicitly deleted because the default definition would be ill-formed:
25 | class Node {
| ^~~~
<source>:25:7: error: no matching function for call to 'Student::Student()'
<source>:13:5: note: candidate: 'Student::Student(int, std::string)'
13 | Student(int grade, string name)
让我为您解释:
您试图使用默认(无参数)构造函数 Node构造 Node()实例。但是- Node是否具有默认构造函数?您会认为它应该,因为您尚未删除它,也未定义任何其他构造函数。
...但这将是一个错误。您会看到,node的字段之一是 Student;而 Node的隐式默认构造函数使用其自己的默认构造函数构造 Node的字段。不幸的是,您通过定义自己的构造函数隐式删除了 Student的默认构造函数。
那你该怎么办?
  • 使Node构造函数采用Student(或const Student&等)。
  • 将代码的最后几行更改为类似
    studentList = new Node(Student(1, "Matei"));
    printList(studentList);

  • PS-在网站上的示例中,请使用 namespace 限定的标识符,例如 std::coutstd::string,并包括其相关的标准库 header 。不要只写 coutstring

    关于c++ - 使用类时如何使用链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64743992/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com