简体   繁体   中英

Operator overloading in C++ - why do we need to pass parameter as const & (…)?

let's say I want to overload an operator ==. I've got a class vector and the following method:

bool operator ==( const Vector & v )
{
    if(( this->x == v.x ) &&( this->y == v.y ) )
         return true;
    else
         return false;

}

Why do I need to pass an object (in this example v) as a constant address to this object? I know - const to force the programmer not to modify the passed object, but why &?

My second question concerns an operator overloading like +=, *= etc. Please, look at this code:

Vector operator +( const Vector & v )
{
    return Vector( this->x + v.x, this->y + v.y );
}

// vs
Vector & operator +=( const Vector & v )
{
    this->x += v.x;
    this->y += v.y;
    return * this;
}

In the second case we can return a new object as well. Why do we return the same, incremented object?

You don't have to do that, it's just desirable to avoid needlessly copying an object.

For your second question, again you don't have to do that, but it makes += operate similarly for Vector as it does for int or double

For the second question: If you write a+=5; or a*=10; you normally expect that the original variable a will be added to or multiplied... If you return original or new object is up to you, but you could confuse other colleagues if you use it counter-intuitively to original meaning...

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