I'm trying to write a doubly linked list for strings with some overloaded operators. I'm not familiar with templates so my list has two classes. One for the node and another for the list itself.
One of the features I'd like to include is an overloaded ++ and -- operator. My goal is to have these work much like the ++ and -- operators on iterators; they update the iterator to point to the next element in the container. However, my implementation isn't working as expected.
I've tried playing with the implementation of the overloaded operator++ by returning a pointer, a reference to a pointer, but neither of them are working as expected. I trimmed down my code to the only applicable 60ish lines and wrote a function called printContents() to exhibit the issue I'm having. When the operator ++ is called within printContents(), the the pointer, p_current_node is updated, but it does not point to the correct address. Could someone please explain why it's not pointing to the correct address and what steps need to be taken to correct it?
Ok, I was able to follow some of that, but I still need some guidance.
Since my structure is a linked list, I want the operator ++ to advance to the next element in the list. Note, I'm not sure if I should be using the pre or post increment. Either way, I want the operator++ to update the object to point to the next element in the list.
For example, the following code iterates through each element of a linked list starting from the root until the last element.
1 2 3 4 5 6
Node* p_current_node = p_root;
while(p_current_node->p_next_node != nullptr){ //iterate through linked list from root
p_current_node = p_current_node->p_next_node;
}
I want to implement the same behavior within my overloaded operator, but I'm not sure how to assign a new value to it. I want to do something like:
Node*& operator++(int){ this = this->p_next_node; returnthis; }
but I don't think I can assign a new value to this.
Do you know how I would assign a value so I could update the Node pointer?
The members of your node are called p_prev_node and p_next_node, so to update the node, you would have to change those members: p_prev_node = p_next_node; p_next_node = p_next_node->p_next_node;, plus checks against null.
Another issue is that in main(), you're working with a pointer and not with any node, so you are not calling your operator++ to begin with. Pointers are not user-defined types and their operators cannot be overloaded.