I am trying to write a program to print all elements of a linked list by recursion. I have used class for implementing the linked list. My program is:
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);
}
}
Compiler is giving message that the error is in definition of print function. I cannot figure out what is the problem. Please help me.
Edit:- The error I am getting is:
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);
The line number in the message is according to the complete program.
As suggested, I removed the default from the definition. But still, I am getting errors though less.
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;
The problem editor is showing is:
a non-static member reference must be relative to a specific object [20,7]
print? You would remove the default from your definitionusing namespace stdwithin global namespace in production code (in quick sketches that is usually fine, though some odd UBs related to component implementation still may happen), in your particular case you barely dodged a problem here because there is anstd::list. You can putusinginside declaration or code blocks, just where you could use a type definition. Embeddingusing namespace stdinto another namespace may lead to ambiguity problems if that namespace would be "used" later