Overloading operator++

  • Thread starter Andreas Mueller
  • Start date
A

Andreas Mueller

Hi,

I want to overload operator++ in my custom iterator class, which I do
like this:

internal struct IListIterator
{
public static IListIterator operator++(IListIterator ii)
{
idx += 1;
// copy at the new position->prefix operator
return new IListIterator(null, idx );
}
}

The question is: Is this the prefix or postfix form? How do both forms
differ in the declaration? I tried the C++ way with an second int as a
parameter, but that of course fails as ++ is an unary operator.

Thanks in advance,
Andy
 
N

Neno Loje [MSP]

Hi Andreas,

in C# the ++ operator does not differentiate between the prefix and postfix
form.

Neno Loje
 
J

Jasper Kent

Not quite. C# requires only one overload of ++ and then works out both
the prefix and the post fix for you. e.g.:

struct Counter
{
private int i;

public static Counter operator ++ (Counter obj)
{
obj.i++;

return obj;
}
}

...

Counter c = new Counter (); // c.i == 0

Counter c1 = ++c; // c.i == 1, c1.i == 1

Counter c2 = c++; // c.1 == 2, c2.i == 1

It's more complex with classes because c, c1 and c2 would all be the
same object, unless you returned a new object from ++, but the basic
idea is the same.

Regards,

Jasper Kent
 
J

Jasper Kent

Here's a class version that gives the same results:

class Counter
{
private int i;

public static Counter operator ++ (Counter obj)
{
Counter temp = new Counter ();

temp.i = obj.i + 1;

return temp;
}
}


Jasper Kent
 
A

Andreas Mueller

Jasper said:
Here's a class version that gives the same results:

class Counter
{
private int i;

public static Counter operator ++ (Counter obj)
{
Counter temp = new Counter ();

temp.i = obj.i + 1;

return temp;
}
}


Jasper Kent

Great, that is doing the job!
Thanks a lot,
Andy
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top