【问题标题】:C++ - Linked List code - LNode was not declared in this scopeC++ - 链表代码 - LNode 未在此范围内声明
【发布时间】:2016-07-08 12:40:00
【问题描述】:

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

运算符是:

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;

我以为我可以在友元函数中实例化一个结构,但它看起来不起作用。有谁知道发生了什么?

【问题讨论】:

    标签: c++ linked-list operator-overloading


    【解决方案1】:

    由于您的operator&lt;&lt; 是一个全局函数,您需要通过以下方式访问您的内部类:

    LList::LNode *np;
    

    由于这个函数是LListfriend,那么它可以访问私有的LNode类。

    【讨论】:

      【解决方案2】:

      由于operator&lt;&lt; 重载是非成员函数,因此您需要使用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】:

        这是因为LNode 不在全局范围内,它是LList 的嵌套类。你必须写:

        ostream & operator << (ostream & outs, const LList & L){ 
            LList::LNode *np = L.first;
            ↑↑↑↑↑↑↑
            /* rest as before */
        }
        

        【讨论】:

          猜你喜欢
          • 2016-02-08
          • 2010-12-17
          • 1970-01-01
          • 2021-07-17
          • 2015-08-21
          • 2015-08-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多