gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 16:53:15 24 4
gpt4 key购买 nike

我有以下类声明:

#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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com