简体   繁体   中英

Why do I need to use a const reference parameter in a << overloading function when using an overloaded post-decrement operator?

I have the following << overloading function:

ostream& operator<<(ostream& output, HW4& rhs)
{

    for(int i = 0; i < HW4::size; ++i)
    {
        output << rhs.array[i] << "    ";
    }

    return output;
}

And I also have this post-decrement overloading function:

HW4 HW4::operator--(int)
{
    HW4 temp = *this;
    int hold;
    for(int i = 0; i < size/2; ++i)
    {
        hold = array[i];
        array[i] = array[size - i - 1];
        array[size - i - 1] = hold;
    }

    return temp;
}

I don't understand why

cout << object2-- << endl << endl;

won't compile unless I change the << overloading function to have a const reference parameter like this

ostream& operator<<(ostream& output, const HW4& rhs)

HW4::operator--(int) returns by value, then what object2-- returns would be a temporary object which can't be bound to an lvalue reference to non-const.

On the other hand, temporary object can be bound to lvalue reference to const . That's why making operator<< taking const HW4& works. Conventionally operator<< is supposed for outputting only, it shouldn't change the object passed; so you should declare operator<< taking const HW4& as the parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM