Suffix Operator Overloading
In order to have a unary operator take the suffix form (be postponed to the
operand), in the operator function definition the parameter list must not be
empty but it has to contain an integer parameter.
Consider the
++ operator.
Prefix version:
Degrees Degrees::operator++()
{
angle = (angle + 1)%360;
return *this;
}
Postfix version:
Degrees Degrees::operator++(int postfix)
{
angle = (angle + 1) % 360;
return *this;
}
Example
#include <iostream>
using namespace std;
class Degrees
{
int angle;
public:
void setAngle(int x)
{
angle = x % 360;
}
int getAngle()
{
return angle;
}
Degrees operator++();
Degrees operator++(int postfix);
};
Degrees Degrees::operator++()
{
angle = (angle + 1) % 360;
return *this; // the left operand is returned
}
Degrees Degrees::operator++(int postfix)
{
angle = (angle + 1) % 360;
return *this; // the left operand is returned
}
int main()
{
Degrees obj1;
obj1.setAngle(190);
++obj1;
cout << obj1.getAngle() << endl;
obj1++;
cout << obj1.getAngle() << endl;
}
Output
191
192