Operator overloading

Feb 21, 2008 at 12:26am
Holy crap

I am not a fan of C++ at all. Stupid professors with stupid operator overloading requirements...

Anyways, for some reason I can't find an example of overloading the '++' operator anywhere on the web. If anyone could perhaps post one or something. that's be awesome. Here's what I have in my main file:

1
2
3
4
ListIterator ListIterator::operator++() {
	currentPtr = this->next;
	return &this;
}


'currentPtr' is a pointer to an element in a list. All user-defined, of course.

Here's the header:

ListIterator operator++();

It seemed pretty simple to me in class, but I can't seem to get it right. I keep trying convert incorrect types and whatnot. I got nothing. Lemme know if more code is necessary.

Oh, and, obviously, the code above is incorrect :)
Feb 21, 2008 at 1:11am
When you try to increment your ListIterator you are probably saying something like this:
my_iter++;
Right? ;-)

The problem is that in C++ there are _two_ increment operators: pre-increment and post-increment. You have overloaded the pre-increment operator. To overload the post-increment operator, you have to give a dummy int argument:
1
2
3
4
5
ListIterator ListIterator::operator++(int) {
	ListIterator result = *this;  // use copy ctor
	currentPtr = this->next;  // increment this
	return result;  // return the _unincremented_ obj
}


Also, watch out for "&this". It should be either "this" or "*this".

Hope this helps.
Feb 21, 2008 at 2:42am
Ok, I tried that, compiled it, and got this:

prog3.cc:8: `class ListIterator' has no member named `next'

Which makes sense, as the 'next' pointer is from the ListElement class. Now I'm just confused.
Last edited on Feb 21, 2008 at 2:48am
Feb 21, 2008 at 3:46am
Me too. (I haven't developed the mental powers to read minds yet.) LOL.
Last edited on Feb 21, 2008 at 3:46am
Feb 21, 2008 at 3:15pm
haha, my bad. I don't wanna put the whole code in here though. I don't know how to break it down, really. Oh well, guess I'll just work on it on my own.

Thanks for the help anways, though!
Topic archived. No new replies allowed.