Reputation: 177
I have the following class declaration:
#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 */
And inside the .cpp file I have the following code for the <<operator:
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;
}
}
Although I declared <<operator as a friend of the class cursor_list, I am unable to access the private member using the class_instance.private_member method. Can someone point out what I am doing wrong?
Upvotes: 1
Views: 106
Reputation: 117298
You need to define operator<<
in the anil
namespace.
namespace anil {
std::ostream& operator<<(std::ostream& out, cursor_list& rhs) {
// ...
return out; // don't forget this
}
}
An easier option is often to just define the friend
function inline:
class cursor_list {
// ...
friend std::ostream& operator<<(std::ostream& out, cursor_list& rhs) {
// ...
return out;
}
};
It's also quite unusual to have non-const
right hand side arguments to operator<<
and I noticed that empty()
and index()
etc. are also non-const
. Perhaps you have reasons for that, but it's worth a note.
Upvotes: 3