问题
I am writing a class for a linked list in C++ and I am having an issue when writing the operator overload for <<. My class' header is:
class LList
{
private:
struct LNode
{
LNode ();
int data;
LNode * next;
};
public:
LList ();
LList (const LList & other);
~LList ();
LList & operator = (const LList & other);
bool operator == (const LList & other);
int Size () const;
friend ostream & operator << (ostream & outs, const LList & L);
bool InsertFirst (const int & value);
bool InsertLast (const int & value);
bool DeleteFirst ();
bool DeleteLast ();
private:
LNode * first;
LNode * last;
int size;
};
and the operator is:
ostream & operator << (ostream & outs, const LList & L){
LNode *np;
np=L.first;
while(np!=NULL){
outs<<np->data;
np=np->next;
}
return outs;
}
When I compile the code I get an error:
LList.cpp: In function ‘std::ostream& operator<<(std::ostream&, const LList&)’:
LList.cpp:36:2: error: ‘LNode’ was not declared in this scope
LNode *np;
^
LList.cpp:36:9: error: ‘np’ was not declared in this scope
LNode *np;
I thought I could instantiate a struct inside a friend function but it looks like that doesn't work. Any of you know what is happening?
回答1:
Since your operator<<
is a global function, you need to access your inner class with:
LList::LNode *np;
Since this function is a friend
of LList
, then it can access the private LNode
class.
回答2:
Since the operator<<
overload is a non-member function, you'll need to use LList::LNode
.
ostream & operator << (ostream & outs, const LList & L){
LList::LNode *np;
// ^^^^^
np=L.first;
while(np!=NULL){
outs<<np->data;
np=np->next;
}
return outs;
}
回答3:
That's because LNode
isn't in global scope, it's a nested class of LList
. You have to write:
ostream & operator << (ostream & outs, const LList & L){
LList::LNode *np = L.first;
↑↑↑↑↑↑↑
/* rest as before */
}
来源:https://stackoverflow.com/questions/36140626/c-linked-list-code-lnode-was-not-declared-in-this-scope