使用类进行实现时,递归打印C++中的链表

Recursively print the linked list in C++ when using class for implementation

本文关键字:打印 递归 C++ 链表 实现      更新时间:2023-10-16

我正在尝试编写一个程序,通过递归打印链表的所有元素。我使用类来实现链表。 我的程序是:

struct node{
int data;
node* link;
};
class list{
node* head;
int size;
public:
list()
{
head=NULL;
size=0;
}
void print(node *temp=head);
void insertpos(int data, int pos);
};
void list::print(node *temp=head)
{
if(temp==NULL)
{cout<<"n";
return;}
else
{
cout<<temp->data<<" ";
print(temp->link);
}
}

编译器给出消息,指出错误在打印函数的定义中。我无法弄清楚问题出在哪里。请帮助我。

编辑:- 我得到的错误是:

error: invalid use of non-static data member 'list::head'
20 |     void print(node *temp=head);
|                           ^~~~
list.cpp:9:11: note: declared here
9 |     node* head;
|           ^~~~
list.cpp:87:29: error: invalid use of non-static data member 'list::head'
87 | void list::print(node *temp=head)
|                             ^~~~
list.cpp:9:11: note: declared here
9 |     node* head;
|           ^~~~
list.cpp:87:6: error: default argument given for parameter 1 of 'void list::print(node*)' [-fpermissive]
87 | void list::print(node *temp=head)
|      ^~~~
list.cpp:20:10: note: previous specification in 'void list::print(node*)' here
20 |     void print(node *temp=head);

消息中的行号是根据完整的程序。

按照建议,我从定义中删除了默认值。但是,我收到的错误虽然更少。

error: invalid use of non-static data member 'list::head'
87 | void list::print(node *temp=head)
|                             ^~~~
list.cpp:9:11: note: declared here
9 |     node* head;

编辑器显示的问题如下:

a non-static member reference must be relative to a specific object [20,7]

我认为这个问题通过以下方式得到解决:https://stackoverflow.com/a/20226907/13123504

如果您无法找到错误的根源,请使用这篇文章作为参考。莱姆知道它是否有帮助!

void list::print(node *temp=head)

是一个错误,应该是

void list::print(node *temp)

在声明函数时指定默认参数,而不是在定义函数时指定默认参数。

更新

另一个错误是不能将成员变量用作默认参数。相反,您应该有两个版本的函数。喜欢这个

class list{
node* head;
int size;
public:
list()
{
head=NULL;
size=0;
}
void print() { print(head); }
void print(node *temp);
void insertpos(int data, int pos);
};

如您所见,现在有两个版本print一个没有参数,另一个只有一个参数。无参数版本仅调用一个参数版本,head作为参数。这就是你以前试图实现的目标。