Operator overloading outside class

Posted by bobobobo on Stack Overflow See other posts from Stack Overflow or by bobobobo
Published on 2010-03-11T14:51:30Z Indexed on 2010/03/13 2:47 UTC
Read the original article Hit count: 581

Filed under:
|

There are two ways to overload operators for a C++ class:

Inside class

class Vector2
{
public:
    float x, y ;

    Vector2 operator+( const Vector2 & other )
    {
        Vector2 ans ;
        ans.x = x + other.x ;
        ans.y = y + other.y ;
        return ans ;
    }
} ;

Outside class

class Vector2
{
public:
    float x, y ;
} ;

Vector2 operator+( const Vector2& v1, const Vector2& v2 )
{
    Vector2 ans ;
    ans.x = v1.x + v2.x ;
    ans.y = v1.y + v2.y ;
    return ans ;
}

(Apparently in C# you can only use the "outside class" method.)

In C++, which way is more correct? Which is preferable?

© Stack Overflow or respective owner

Related posts about c++

Related posts about operator-overloading