Solved

how to override ++ operator in this case

Posted on 2007-11-24
7
508 Views
Last Modified: 2013-12-14
I'm constructing a class for a double linked list's node. I want to overrid ++ operator such as this code. But I know that this pointer in C++ is cannot be assignet value. Please, someone can suggest an idea for this situation. Thanks a lot


#include <iostream>

using namespace std;
 

//Basic Doubly Linked List node class. 

class DLLNode

{

public:

	DLLNode() //Default Constructor

	{

		p_data = 0;    //No data.

		p_next = NULL; //New node always has a NULL next node.

		p_prev = NULL; //New node always has a NULL previous node.

	}

	DLLNode(unsigned int data) //Constructor

	{

		p_data = data; //No data.

		p_next = NULL; //New node always has a NULL next node.

		p_prev = NULL; //New node always has a NULL previous node.

	}

	unsigned int data(void) const //Retreive the data of the node. Constant function.

	{

		return p_data;

	}

	DLLNode* prev(void) const //Retreive the preivous pointer of the node. Constant function.

	{

		return p_prev;

	}

	DLLNode* next(void) const //Retreive the previous pointer of the node. Cosntant function.

	{

		return p_next;

	}

	void setdata(unsigned int data) //Set the data of the node. 

	{

		p_data = data;

	}

	void setprev(DLLNode* prev) //Set the previous pointer of the node.

	{

		p_prev = prev;

	}

	void setnext(DLLNode* next) //Set the next pointer of the node.

	{

		p_next = next;

	}
 

private:

	unsigned int p_data; //Data stored by the node. protected.

	DLLNode* p_prev;     //Pointer to the next node. protected.

	DLLNode* p_next;     //Pointer to the previous node. protected.

};
 

ostream& operator << (ostream& out, DLLNode& node) //Output the data of a node.

{

	out << node.data() << " "; //Output the data of the node, followed by a space.

	return out;                //Return the output stream.

}
 

void operator ++ ()

{

       this = p_next;

}

Open in new window

0
Comment
Question by:meoconx
7 Comments
 
LVL 6

Expert Comment

by:SeanDurkin
ID: 20343051
Does this explanation of the increment operators help?

http://www.thes0urce.net/articles/incr_decr_ops.html

I don't understand how you traverse your list with the DLLNode class. Usually if you want to create a list, you have two separate classes, one for List and one for Node, and then possibly one for ListIterator (in which you implement the ++ and -- operators, to traverse the list).
0
 
LVL 28

Accepted Solution

by:
pepr earned 65 total points
ID: 20344251
It is not clear what is the purpose of your ++ operator. I guess that increasing the data value is not the goal. Possibly, you want to add a new list node in front of just after this node.

The operator ++ can have prefix or postfix form (like ++i or i++). The usual interpretation is "increase the original and return the new value" for the prefix form and "return the old value and increase the internal value". For the double linked list the interpretation could be different -- like insert the new node in front of this node for the prefix form, and insert the new node after this node for the postfix form. Anyway, you should return reference to some node (old or new). In both cases, you must create new node (using the new operator for the DLLNode class), bind the p_next and p_prev pointers of the new node to the nodes in front and after the new node. You have to update also the p_next pointer of the previous node and p_prev pointer of the next node.

The operator++() denotes the prefix form, the operator+(int) with dummy int says the compiler that this is the postfix version of the operator.


prefix form -- insert the new node
0
 

Author Comment

by:meoconx
ID: 20344640
I want to override operator ++ just for change the pointer from the current node to its next node.
eg:
tmp++ is the same to tmp = tmp->p_next;
is there any way to use with postfix form?
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:meoconx
ID: 20344645
this is just a problem which my friend asked me to solve.
0
 
LVL 6

Assisted Solution

by:SeanDurkin
SeanDurkin earned 60 total points
ID: 20344800
When you do something like this:

tmp = tmp->p_next;

You're changing the value of tmp (DLLNode *), so it now points to a new DLLNode object (specifically, whatever old tmp's p_next pointed to). This is different from changing the actual class. You're changing a pointer to a DLLNode object, not the object itself. If you were to implement a ++ operator and do something like:

(*tmp)++;

That would be changing the actual object, which is not what you want. Therefore, if you were to implement some kind of iterator for your list of DLLNodes, you would need a separate class to link them together in a list, and then iterate that list. You can't iterate to the next node of a list inside a node class, because the node class is just a node - it can't see the whole list (like an iterator can).

To help clarify things for you, I've attached sample header file code for implementing a doubly linked list (it was an assignment we had in one of the classes I took). Hope this helps:
#include <iostream>

#include <cstdlib>

using std::cout;

using std::endl;
 

// forward declaration of List class, so ListElement can make 

// it a friend.  NOTE: If List is a friend of ListElement, that

// means that the List class has access to the private members

// of the ListElement class, but no one else does (besides ListElement

// itself). 
 

class List;

class ListIterator;
 

class ListElement {

 friend class List;

 friend class ListIterator;

 public:

 ListElement(): next(this), prev(this), isHeader(true) {}

 ListElement(int i): item(i), isHeader(false) {}

 ~ListElement() {}  // default destructor

 private:

  int item;

  ListElement *next;    

  ListElement *prev;    

  bool isHeader;

};
 

class ListIterator {

 friend class List;

 public:

  ListIterator() : currentPtr(NULL) { }

  ListIterator operator++();  // advance iterator to the next list node; return value is iterator *after* advancing

  ListIterator operator--();  // advance iterator to the previous list node; return value is iterator *after* advancing

  ListIterator operator++(int);  // advance iterator to the next list node; return value is iterator *before* advancing

  ListIterator operator--(int);  // advance iterator to the previous list node; return value is iterator *before* advancing

  int operator*(); // return contents pointed to by iterator; print "error"

                   // and terminate program if iterator refers to header node

 private:

  ListElement *currentPtr;

};
 

class List {

  public:

    List();   // creates an empty list

    ~List();  // *must* deallocate the entire list

    List(const List &L);  // copy constructor (*must* be a deep copy)

    List & operator =(List &L);  // *must* (deep) copy list, must avoid memory leak,

                                 // and must handle self-assignment
 

    // these are functions to set and test the list iterator

    void SetStartList(ListIterator &p) {p.currentPtr = head->next;}

    void SetEndList(ListIterator &p) {p.currentPtr = head->prev;}

    bool IsUndefined(ListIterator p) {return (p.currentPtr == head);}

    bool AtEndList(ListIterator p) {return (p.currentPtr == head);}

    bool AtStartList(ListIterator p) {return (p.currentPtr == head);}

    bool AtFirstNode(ListIterator p) {return (p.currentPtr == head->next);}

    bool AtLastNode(ListIterator p) {return (p.currentPtr == head->prev);}
 

    // Insert integer at the beginning of the list  

    void Prepend(int it); 
 

    // Insert integer at the end of the list

    void Append(int it);  
 

    // Remove first integer from list, return through first parameter.

    // Success is set to true if original list is nonempty, false if empty

    void Pop(int &it, bool &success); 
 

    // Remove last integer from list, return through first parameter.

    // Success is set to true if original list is nonempty, false if empty

    void Pull(int &it, bool &success); 
 

    // Get first integer on list, return through first parameter

    // Success is set to true if original list is nonempty, false if empty

    void First(int &it, bool &success);
 

    // Get last integer on list, return through first parameter

    // Success is set to true if original list is nonempty, false if empty

    void Last(int &it, bool &success);
 

    // insert integer before list element referred to by p

    void InsertBefore(int it, ListIterator p);
 

    // insert integer after list element referred to by p

    void InsertAfter(int it, ListIterator p);
 

    // delete list element referred to by p; print "error"

    // and exit if p refers to the header node

    // p is undefined after this function

    void Delete(ListIterator p);
 

    // apply function "func" to each element on the list

    void MapFunction(void (*func)(int &));
 

    // returns true if list empty, false otherwise

    bool IsEmpty();     
 

    int GetSize() {return listSize;}
 

    // must print out list elements, one per line

    void Print(); 
 

  private:

    ListElement *head;

    int listSize;

};

Open in new window

0
 

Author Comment

by:meoconx
ID: 20345024
thanks for all.
0
 
LVL 4

Expert Comment

by:yuy2002
ID: 20345092
In C++, the prefix ++ function for a class-name is defined with the template:

   class-name operator++();

class-name class-name:: operator++(){
  logic to increment class-name
  return *this;
}

To define the the postfix ++ function, one uses:
String operator++(int x);

Note that the parameter is not used in the method. It is just a way that one can distinguish prefix increment operators from postfix increment operators.

The definition looks as follows:


class-name class-name:: operator++(int garbage){ // postfix operator, return original value
  class-name Return;
  Return = *this;
  increment class-name
  return Return;
}

Observe that we copy the object before incrementing it. That way, this value can be defined.

If u define a postfix ++ , you can follow the below code:
DLLNode DLLNode:: operator++(int garbage){
    return *p_next;
}

However this pointer won't be changed, so if u want to traverse the double linked list, u'd better to use
a point which some like iterator in stl.  
SeanDurkin has offerd the code, u can refer to it.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now