友元函数无法访问私有结构

friend function can't access private struct

本文关键字:结构 访问 函数 友元      更新时间:2023-10-16

我正试图编写一个friend函数来遍历链表并输出列表中的字符,但由于某些原因,我无法在friend函数中声明Nodes。这是我的代码:

这就是功能:

std::ostream& operator<<(std::ostream& out, LinkedList& list)
  {
      Node *tempNode = nullptr;
      *tempNode = *beginningOfList;
      std::cout << "list: ";
      while(tempNode)
      {
          std::cout << tempNode->letter;
          if (tempNode->next)
              std::cout << ", ";
          tempNode = tempNode->next;
      }
      return out;
  }

这是头文件:

  #ifndef _LINKED_LIST_
  #define _LINKED_LIST_
  #include <ostream>
  class LinkedList
  {
  public:
     LinkedList();
     ~LinkedList();
     void add(char ch);
     bool find(char ch);
     bool del(char ch);
     friend std::ostream& operator<<(std::ostream& out, LinkedList& list);
  private:
      struct Node
      {
          char letter;
          Node *next;
      };
      Node *beginningOfList;
  };
  #endif // _LINKED_LIST_

当我试图编译它时,我会收到消息"Node未在此范围内声明"、"*tempNode未在此作用域内声明"answers"*beginingOfList未在此作用区内声明"。我猜问题与命名空间有关,但我真的不确定。

这是在说实话。未在该范围中声明节点等。您的运算符是一个全局函数,但这些都在LinkedList的范围内。尝试将它们称为LinkedList::Node、list->beginingOfList等。