c++ - friend std::ostream& operator<< 声明不允许我访问类的私有(private)成员

标签 c++ namespaces operator-overloading

我有以下类声明:

#ifndef ANIL_CURSOR_LIST_H
#define ANIL_CURSOR_LIST_H

#include <cstddef>
#include <iostream>

namespace anil {
  class cursor_list_node {
    private:
      int data;
      cursor_list_node* next;
      cursor_list_node* previous;
      friend class cursor_list; 
  };

  class cursor_list {
    private:

      // Data:
      int m_index;
      int m_size;
      cursor_list_node* front;
      cursor_list_node* back;
      cursor_list_node* cursor;

      // Functions:
      void delete_list();

    public:
      cursor_list() : m_index(-1), m_size(0), front(nullptr), back(nullptr),
        cursor(nullptr) {}
      cursor_list(cursor_list& copied_list);
      bool is_empty();
      int size();
      int index();
      int front_data();
      int back_data();
      int cursor_data();
      bool operator==(cursor_list& rhs); // rhs = right hand side
      cursor_list& operator= (cursor_list& rhs);  // rhs = right hand side
      friend std::ostream& operator<<(std::ostream& out, cursor_list& rhs); // rhs = right hand side
      void clear();
      void move_cursor_front();
      void move_cursor_back();
      void move_cursor_prev();
      void move_cursor_next();
      void prepend(int new_data);
      void append(int new_data);
      void insert_before_cursor(int new_data);
      void insert_after_cursor(int new_data);
      void delete_front();
      void delete_back();
      void delete_cursor();
      ~cursor_list();
  };
}

#endif /* ANIL_CURSOR_LIST_H */
在 .cpp 文件中,我有以下 <std::ostream& operator<<(std::ostream& out, anil::cursor_list& rhs) { if (rhs.is_empty() != false) { anil::cursor_list_node* back_up_cursor = rhs.cursor; int back_up_index = rhs.index(); for (rhs.move_cursor_front(); rhs.index() >= 0; rhs.move_cursor_next()) { if (rhs.cursor == rhs.front) { out << rhs.cursor_data(); } else { out << ' ' << rhs.cursor_data(); } } rhs.m_index = back_up_index; rhs.cursor = back_up_cursor; } } 尽管我将 <

最佳答案

您需要定义 operator<<anil命名空间。

namespace anil {
std::ostream& operator<<(std::ostream& out, cursor_list& rhs) {
    // ...
    return out; // don't forget this
}
}
一个更简单的选择通常是定义 friend内联函数:
class cursor_list {
    // ...
    friend std::ostream& operator<<(std::ostream& out, cursor_list& rhs) {
        // ...
        return out;
    }
};
const 也很不寻常。 operator<< 的右侧参数我注意到 empty()index()等也是非const .也许你有理由这样做,但值得一提。

关于c++ - friend std::ostream& operator<< 声明不允许我访问类的私有(private)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68316999/

相关文章:

c++ - 枚举和枚举类的链接兼容性

c++ - 使用 step 方法检索图像的 bgr 值的代码有什么问题

c++ - 私有(private)类成员没有完全封装?

c++ - 确保在 C++ 编译时正确的双指针传递方法

c# - 在不知道内部名称的情况下从外部访问内部命名空间

c# - 找不到命名空间或数据类型 NavMeshAgent Unity 3d

c++ - 使用命名空间的全局变量

c# - 为什么 '='不能在C#中重载?

c# - 嵌套隐式运算符

c++使用多重继承调用基类的虚拟运算符==