templates - Printing Objects via "<<" in a Linked-List in C++ -
for assignment (and myself) need able print singlely linked list of "stock" objects.
each stock following private data members: 1 int 1 string
this print function in linked list class had use/develop. not allowed use stl::list().
//list.h template<class nodetype> void list< nodetype>::print() const { if(isempty() ){ cout<<"the list empty\n\n"; return; } listnode< nodetype> *currentptr=firstptr; cout<<"the list is: "; while (currentptr!=0){ //cout << currentptr->data << ' '; currentptr = currentptr->nextptr; } cout<< "\n\n"; }
now nodes in list, listnode.h:
//listnode.h //listnode template definition #ifndef listnode_h #define listnode_h template< class nodetype > class list; template < class nodetype> class listnode { friend class list < nodetype>; public: listnode (const nodetype &); //constructor nodetype getdata() const; private: nodetype data; listnode< nodetype> *nextptr; }; template<class nodetype> listnode< nodetype >::listnode(const nodetype &info): data (info), nextptr(0) { } template<class nodetype> nodetype listnode<nodetype>::getdata() const{ return data; } #endif
now stock class:
class stock{ public: stock(); //default constructor stock(string, int); //overloaded constructor ~stock(); //deconstructor void setsymbol(string); //sets stock symbol void setshares(int); string getsymbol(); int getshares(); private: string symbol; int shares; }; stock::stock(){ symbol=" "; shares=0; } stock::stock(string s, int num){ cout<<"creating stock supplied values! \n\n"<<endl; symbol=s; shares=num; price=p; }
simple int main() testing:
int main(){ list < stock > portfolio_list; stock google("goog", 500); stock vmware("vmw", 90); stock apple("apl", 350); portfolio_list.insertatfront(google); portfolio_list.insertatfront(vmware); portfolio_list.insertatfront(apple); portfolio_list.print(); return 0; }
so obviously, operator errors "<<" in list.h, because can't output contents of stock class. end goal loop through every element in linked list , print string symbol , int. i'm assuming need use sort of operator overloading? or way off base? if do, should implemented in stock class? in advance.
if understood code, you'll have overload <<
operator both listnode
, list
classes.
//representation of listnode template <class t> ostream& operator << (ostream& ostr, listnode<t>& ls) { return ostr << "foo"; //replace "foo" proper representation } //representation of list template <class t> ostream& operator << (ostream& ostr, list<t>& ls) { ostr << "[ "; for(listnode<t> *i = ls.firstptr; != null; = i->nextptr) ostr << *i << " "; return ostr << "]"; }
would print [ foo foo foo ]
3 element list.
btw, should mark functions friend
if need access private members.
Comments
Post a Comment