Pages

Saturday, January 2, 2010

Postfix operator

If we have an object x of a class XClass and we need both statements x++ and ++x be properly executed, we need to overload bot postfix and prefix perators. For example as it is in the following program:
#include <iostream>
using namespace std;

class Test
{
int x;
public:
Test() : x(0) {}

Test operator++()
{
x++;
return *this;
}

Test operator++(int)
{
x++;
return *this;
}

int X() { return x; }

void Out()
{
cout << "x = " << x << endl;
}
};

int main()
{
Test test;
test.Out();

++test;
test.Out();

test++;
test.Out();

return 0;
}

As you see the postfix operator has int in parentheses. It is a signal to the compiler to generate the postfix version of the operator.

No comments:

Post a Comment