我正在用 C++ 为链表编写一个类,但在为 << 编写运算符重载时遇到问题。我类的标题是:
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;
};
运算符(operator)是:
ostream & operator << (ostream & outs, const LList & L){
LNode *np;
np=L.first;
while(np!=NULL){
outs<<np->data;
np=np->next;
}
return outs;
}
编译代码时出现错误:
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;
我以为我可以在友元函数中实例化一个结构,但它看起来不起作用。你们有人知道发生了什么吗?
最佳答案
由于您的 operator<<
是一个全局函数,你需要访问你的内部类:
LList::LNode *np;
因为这个函数是一个 friend
的 LList
, 然后它可以访问私有(private) LNode
类。
关于C++ - 链接列表代码 - LNode 未在此范围内声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36140626/