I'm working through an assignment in which I must overload the insertion operator to take a Node object. I've created the operator overload function outside the class definition, but inside the node.h file. Everything compiles fine, but the overloaded operator is not called, instead I get simple the address of the object.
I'm prohibited from modifying the calling code, so any changes must be to the operator overload.
My code as it stands right now:
/** OPERATOR << ***********************************/
template<class T>
inline std::ostream & operator << (std::ostream & out, const Node <T> *& pHead)
{
out << "INCOMPLETE";
return out;
}
Right now, I just want to ensure the overloaded operator is called. I'll fix the output code once I know I'm calling the right operator.
The calling code:
// create
Node <char> * n = NULL;
// code modifying n
// display
cout << "\t{ " << n << " }\n";
Note that the parameter pHead
's type is a reference to non-const, const Node<T>*
is a non-const pointer to const, the argument n
's type is Node<T>*
(i.e. a non-const pointer to non-const). Their type doesn't match, Node<T>*
need to be converted to const Node<T>*
, which is a temporary and can't be bound to reference to non-const.
In short, you can't bind a reference to non-const to an object with different type.
But reference to const could be bound to temporary, so you can change the parameter type to reference to const:
template<class T>
inline std::ostream & operator << (std::ostream & out, const Node <T> * const & pHead)
// ~~~~~
Or change it to passed-by-value, Node<T>*
will be implicitly converted to const Node<T>*
when passing as argument. (Passing pointer by reference to const doesn't make much sense.)
template<class T>
inline std::ostream & operator << (std::ostream & out, const Node <T> * pHead)
At last, overloading operator<<
with pointer type looks weird. The most common form with user-defined type would be:
template<class T>
std::ostream & operator << (std::ostream & out, const Node <T> & pHead)