c++ - ostream must take exactly one argument -
i getting compile error in output stream operator , cannot seem find out how fix never received error before:
linkedlist.cpp:258: error: ‘std::ostream& linkedlist<t>::operator<<(std::ostream&, linkedlist<t>)’ must take 1 argument make: *** [linkedlist.o] error 1 here definition of operator<<
template <class t> ostream& linkedlist<t>::operator<<(ostream &output, linkedlist<t> list) { node *curr; curr=list.head; while(curr!=null ) { output << curr->data; curr = curr->next; } return output; } here in header:
//ostream operator printing list template <class t> ostream &operator<<(ostream &output, linkedlist<t> list); any appreciated!
you defined member function, have define free standing (probably friend) function, either
outside class
template <class u> ostream& operator<<(ostream &output, linkedlist<u> list){...}
in case have declare inside class
template <class u> // note different type name friend ostream& operator<<(ostream &output, linkedlist<u> list) or
inside class as
// no need template, type passed automatically function not templated anymore friend ostream& operator<<(ostream &output, linkedlist list){...}
the difference between these 2 declarations bit subtle, purpose both work equally well. , want pass linkedlist const reference, linkedlist<t>& list.
edit
a common mistake declare friend operator inside class as
template<typename t> class linkedlist { //.... friend ostream& operator<<(ostream& output, const linklist& list); // declaration } then try define outside class as
template<typename t> ostream& operator<<(ostream& output, const linklist<t>& list){...} guess what? code compile, won't link, declaration inside class declares non-template function, 1 each type t pass linklist<t>. then, when declare e.g. linklist<int> lst, , try cout << lst, compiler see declaration of friend, looks like
friend ostream& operator<<(ostream& output, const linklist<int>& list); and try searching definition. there no definition in rest of header, template operator, linker isn't able find implementation , spit linker error. live example here.
Comments
Post a Comment