c++ post and pre increment operators - slightly off topic
Gianni Mariani
marianig@orconet.com
Tue Jul 25 17:57:00 GMT 2000
Please excuse my digression, it seems I have run out of other
references.
It seems c++ post increment methods don't happen post the expression.
A class that implements operator++() operator++(int) and operator*()
does not behave like (I at least) expected.
int i = * pointer_val ++;
Seems to behave differently if pointer_val is a real pointer. The post
increment operator happens BEFORE the reference.
Am I missing somthing. Same thing happens on windoze.
------- output of the code below --------
perator++(int) called
operator*() called
operator++() called
operator*() called
x1=1 x2=1 <<< --
x1=0 x2=1 <<< -- expected these 2 lines to be the same.
------- the code below ----------
#include <iostream.h>
class foo {
public:
int i;
foo( int x = 0 )
: i( x )
{
}
int operator*()
{
cout << "operator*() called\n";
return i;
}
foo operator++()
{
cout << "operator++() called\n";
++ i;
return * this;
}
foo operator++(int num)
{
cout << "operator++(int) called\n";
i ++;
return * this;
}
};
int intbar[] = { 0, 1, 2 };
main()
{
foo foobar1;
foo foobar2;
int x1 = *foobar1++;
int x2 = *++foobar2;
cout << "x1=" << x1 << " x2=" << x2 << endl;
int * intbar1 = intbar;
int * intbar2 = intbar;
x1 = *intbar1++;
x2 = *++intbar2;
cout << "x1=" << x1 << " x2=" << x2 << endl;
}
[gianni@uluru ds]$ ls
Debug/ ccstring.cpp ccstring.h jjnk.cpp* jjnk.dsp* jjnk.ncb*
jjnk.plg*
[gianni@uluru ds]$ cat jjnk.cpp
#include <iostream.h>
class foo {
public:
int i;
foo( int x = 0 )
: i( x )
{
}
int operator*()
{
cout << "operator*() called\n";
return i;
}
foo operator++()
{
cout << "operator++() called\n";
++ i;
return * this;
}
foo operator++(int num)
{
cout << "operator++(int) called\n";
i ++;
return * this;
}
};
int intbar[] = { 0, 1, 2 };
main()
{
foo foobar1;
foo foobar2;
int x1 = *foobar1++;
int x2 = *++foobar2;
cout << "x1=" << x1 << " x2=" << x2 << endl;
int * intbar1 = intbar;
int * intbar2 = intbar;
x1 = *intbar1++;
x2 = *++intbar2;
cout << "x1=" << x1 << " x2=" << x2 << endl;
}
More information about the Gcc-help
mailing list