c++ - Why does dereferencing nodes break my linked-list? -


so i'm trying implement run of mill linked list in c++

template<class t> class node { private:     node *next;     t item;  public:     node(t item)         : item(item)     {         this->next = null;     }      node<t> add(t item) {          this->next = new node(item);          return *this->next;     }      bool hasnext()     {         return this->next == null;     }      node<t> getnext()     {         return *this->next;     }      t value()     {         return this->item;     } };  void main() {     node<int> node(3);     node.add(3).add(4);      cout << node.value();     cout << node.getnext().value();     cout << node.getnext().getnext().value();      cin.get(); } 

but can't work. in particular section:

    node.add(3).add(4);      cout << node.value();     cout << node.getnext().value();     cout << node.getnext().getnext().value(); 

if change add , getnext functions return node<t>* instead of node<t>, works fine. why dereferencing cause code break? think . notation makes more sense ->, can't work. doing wrong?

right making copy of node added rather returning actual node created. parenthesis add bit of clarity other people have @ code later. add function needs changed this:

node<t>& add(t item) {      this->next = new node(item);      return *(this->next); } 

or return pointer newly created node, breaks using . rather -> in main.

also similar changes need made next()


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -