user3347541
user3347541

Reputation: 27

Making prefix operator do nothing on certain circumstances

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

Answers (1)

iavr
iavr

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

Related Questions