C++ - 链表代码 - LNode 未在此范围内声明
C++ - Linked List code - LNode was not declared in this scope
我正在为 C++ 中的链表编写 class,但在为 << 编写运算符重载时遇到问题。我的 class' header 是:
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;
};
运算符是:
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<<
是一个全局函数,您需要使用以下方法访问您的内部 class:
LList::LNode *np;
因为这个函数是LList
的friend
,所以它可以访问私有的LNode
class.
由于 operator<<
重载是一个非成员函数,您需要使用 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;
}
那是因为 LNode
不在全局范围内,它是 LList
的嵌套 class。你必须写:
ostream & operator << (ostream & outs, const LList & L){
LList::LNode *np = L.first;
↑↑↑↑↑↑↑
/* rest as before */
}
我正在为 C++ 中的链表编写 class,但在为 << 编写运算符重载时遇到问题。我的 class' header 是:
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;
};
运算符是:
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<<
是一个全局函数,您需要使用以下方法访问您的内部 class:
LList::LNode *np;
因为这个函数是LList
的friend
,所以它可以访问私有的LNode
class.
由于 operator<<
重载是一个非成员函数,您需要使用 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;
}
那是因为 LNode
不在全局范围内,它是 LList
的嵌套 class。你必须写:
ostream & operator << (ostream & outs, const LList & L){
LList::LNode *np = L.first;
↑↑↑↑↑↑↑
/* rest as before */
}