Reputation: 27
Overloading postfix operator doesn't work
Here was my program yesterday after i fixed it. I am having trouble to negate the prefix operator from doing anything if my hours and days are set @ zero.
NumDays NumDays::operator--()
{
--hour;
simplify();
return *this;
}
NumDays NumDays::operator--(int)
{
NumDays obj1(*this);
if(day == 0 && hour > 0)
{ hour--; }
simplify();
return obj1;
}
If i try to use the if state like the postfix operator, both of my operators will not work even if the day and hours are not @ 0. How do i make the prefix operator do nothing if day and hour is at 0?
Upvotes: 0
Views: 43
Reputation: 7647
First, your logic seems incorrect, as pointed out by Wimmel. I think you want to disable operator--
only when both day,hour
are zero.
Second, the prefix operator should return a reference.
Third, you may have the postfix operator use the prefix one, so you don't duplicate code.
All in all:
NumDays& NumDays::operator--()
{
if (day > 0 || hour > 0)
{
--hour;
simplify();
}
return *this;
}
NumDays NumDays::operator--(int)
{
NumDays copy(*this);
++(*this);
return copy;
}
Upvotes: 1