The answer by Xirema already answers your question.
I just want to point out that if you support f-1
as an operator function, there are several operators that you should also support.
Fortunately, you can re-use some of the implementations to implement others.
Here's my suggestion:
struct foo
{
int a=5;
int b=4;
int c=8;
// Pre-increment
foo& operator++()
{
++a;
++b;
++c;
return *this;
}
// Post-increment
foo operator++(int)
{
foo copy = *this;
++(*this);
return copy;
}
// Pre-decrement
foo& operator--()
{
--a;
--b;
--c;
return *this;
}
// Post-decrement
foo operator--(int)
{
foo copy = *this;
--(*this);
return copy;
}
// Increment
foo& operator+=(int v)
{
a += v;
b += v;
c += v;
return *this;
}
// Decrement
foo& operator-=(int v)
{
// Use the inrement operator.
return ( (*this) += (-v));
}
// Addition
foo operator+(int v) const
{
foo copy = *this;
copy += v;
return copy;
}
// Subtraction
foo operator-(int v) const
{
// Use the addition operator.
return ((*this) + (-v));
}
};
Test code:
int main()
{
foo f1;
// Pre-increment
++f1;
// Post-increment
f1++;
// Pre-decrement
--f1;
// Post-decrement
f1--;
// Increment
f1 += 10;
// Decrement
f1 -= 20;
// Addition
foo f2 = f1 + 20;
// Subtraction
foo f3 = f2 - 50;
}