C++ Insertion operator overload (<<)

我怕爱的太早我们不能终老 提交于 2019-12-13 15:19:30

问题


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";

回答1:


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)



回答2:


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.



来源:https://stackoverflow.com/questions/40179620/c-insertion-operator-overload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!