I have to overload the insertion operator in order to view my class objects in matrix format. I wrote the code but something’s wrong. When I include this to my code and trying to build, compiler gives me tons of errors; when I commented that part out, the errors are gone and program works correctly. Here is the code:
template <class itemType>
ostream & operator<< (ostream & os, const Storage2D<itemType> & rhs)
{
node<itemType>* ptrRow = rhs.head;
node<itemType>* ptrColumn = rhs.head;
for(; ptrColumn->down != NULL; ptrColumn = ptrColumn->down)
{
ptrRow = ptrColumn;
for(; ptrRow->right != NULL; ptrRow = ptrRow->right)
{
os << ptrRow->info << setw(10);
}
os << ptrRow->info << setw(10) << endl;
}
return os;
}
Here is how I tried to use overloading from main function:
Storage2D<double> m(row, column);
cout << m;
It is not the member function of class Storage2D, it is written outside of the scope of class Storage2D in the implementation file.
It would be great if you help me, thanks in advance.
EDIT: Here is the rest of my code. The Storage2D.h file:
template <class itemType>
struct node
{
itemType info;
node* right;
node* down;
node()
{}
node(itemType data, node* r = NULL, node* d = NULL)
{
info = data;
right = r;
down = d;
}
};
template <class itemType>
class Storage2D
{
public:
Storage2D(const int & , const int & ); //constructor
//~Storage2D(); //destructor
//Storage2D(const Storage2D & ); //deep copy constructor
private:
node<itemType>* head;
};
ostream& operator<< (ostream & os, const Storage2D & rhs);
#include "Storage2D.cpp"
headis private so the operator needs to be a friend so it can access that data member. It also needs to be declared as a function template since Storage2D is a class template:Note that I have explicitly used
std::ostream, sinceostreamis in thestdnamespace.