C++ - 链接列表代码 - LNode 未在此范围内声明

标签 c++ linked-list operator-overloading

我正在用 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;

因为这个函数是一个 friendLList , 然后它可以访问私有(private) LNode类。

关于C++ - 链接列表代码 - LNode 未在此范围内声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36140626/

相关文章:

c - 从 C 中的不兼容指针类型警告返回

c++ - 将多个运算符与运算符重载一起使用会产生奇怪的错误

<< 运算符的 c++11 特定重载

c++ - 遍历整个图的最小节点数

c++ - StartService FAILED 577自签名内核驱动程序,如何解决?

c++ - 将 C 风格程序转换为 C++

c++ - 查找点 vector 的最小值和最大值

java - addFirst 方法在自定义 linkedList 中无法正常工作

使用 pop_back 的 C++ 析构函数

c++ - 运算符重载 C++ 中的友元函数与成员函数