简体   繁体   中英

C++ Insertion operator overload (<<)

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>* (ie 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)

The problem is that the inserter takes a parameter of type const Node<T>* , but it's called with an argument of type Node<T>* ; there is no conversion from T* to const T* . So the "fix" is to remove the const from the stream inserter.

But, as hinted at in a comment, having an inserter that takes a pointer to a type is a bad idea. It should take a const Node<T>& , like all the other inserters in the world. I gather that this is a constraint imposed by an assignment; if so, it's idiotic. You're being taught badly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM