I want to overload the operator << to print a list using std::cout, for example:
std::cout << list
//ouputs as {1,2,3,..}
After searching, I came to know that this can be done using ostream, but I am not sure how this is done. Like why is this necessary to take in ostream as a reference and then return it?
Operator Overloading function:
ostream& operator<<(ostream& os, List list)
{
Node* temp = list.start; //points to the start of the list
cout<<"{";
while(temp)
{
cout << temp->data; //cout all the data
if (temp->next != NULL)
cout << ",";
temp = temp->next;
}
cout<<"}" << endl;
return os; //returns the ostream
}
And I also don't understant why do we have to make that a friend function? If I remove the keyword friend, it gives me an error that << operator is a binary operator. I am using Xcode.
List.hpp
class List
{
Node* start;
public:
List();
~List();
void emptyList();
void append(int);
void insert(int, int);
void print();
int length();
void remove_at(int);
int get_value_index(int);
int get_value_at(int);
List operator-(int);
friend ostream& operator<<(ostream& os,List); //why friend function??
List operator=(List);
List operator+(int);
List operator+(List);
int& operator[](const int ind);
bool operator==(List);
};