使用类进行实现时,递归打印C++中的链表
Recursively print the linked list in C++ when using class for implementation
我正在尝试编写一个程序,通过递归打印链表的所有元素。我使用类来实现链表。 我的程序是:
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
作为参数。这就是你以前试图实现的目标。
相关文章:
- 数组元素打印的递归方法
- 如何在C++中递归地按相反顺序打印集合
- 如何使用递归打印修改后的星号三角形图案
- 为什么我的递归函数按降序打印,然后按升序打印?
- 使用递归 c++ 打印模式
- 使用递归反转和打印出数组的内容
- 我在 C++ 中创建了一个函数来递归反转字符串,但是之后如何使功能打印一个 endl?
- 使用类进行实现时,递归打印C++中的链表
- 如何使用递归打印最长公共子序列中涉及的字符串?
- 递归回溯打印长度为N的二进制数的所有组合,而不使用循环
- C++从递归函数中打印出奇怪的字符
- 使用递归打印所有递增子序列
- 二叉搜索树按级别递归C++打印节点
- 如果找不到解决方案,我如何留下递归循环,而不会打印任何东西
- 在1个功能中打印相反的三角递归C
- 使用递归打印输出
- 如何使用递归打印文本反驳
- 如何使用递归按从 1 到 n 的升序打印数字,其中 n 在该函数的参数中给出
- 如何打印递归 lambda 模板的名称
- 如何在递归函数中打印向量