简体   繁体   中英

Recursive data structure in c++

I'm implementing a recursive data structure in c++ using classes. I'm having some trouble implementing it particularly with the "this" pointer.

In one function, I need to modify the "this" pointer. However that is not allowed. How do I do it? I read somewhere that you will need to pass "this" pointer to that function to change it. However I'm not clear with that. Does that behave like python's "self"? An example would be great

EDIT:

void insert(int key)
{
    if (head == NULL)
    {
        /* I need to insert in beginning of structure */
        List* tmp;
        tmp->key = key;
        tmp->next = this;
        this = tmp;  /* This does not work */
    }
}

Thank You!

You cannot modify the this pointer, given that it behaves as if declared T* const . What you could do is hold a pointer to your own type inside of the class, and modify that.

class foo
{
    /* ... */
private:
    foo* p; // this can be modified
};

You cannot modify this , period. You need to re-structure your program so that you don't need to do that.

The best way to insert the way you're trying to is to create a double linked list, not a single one (with only the next pointer). In other words, you should have a previous pointer that points to the previous node in the list to properly insert using the this pointer. Else you need to insert from the parent node of the this.

ie with a double linked list:

Node* tmp = new Node;
tmp->key = key;
this->previous->next = tmp;
tmp->previous = this->previous;
tmp->next = this;
this->previous = tmp;

Edit: Don't forget that "this" is ""simply"" a memory address so what you want to change is what's contained in it.

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