简体   繁体   中英

C++ member vs non-member operator+

I saw 2 different approaches for implementing operator+ .

In the standard library, std::complex , operator+ is implemented as non-member function. In Vector2 class used at work operator+ is implemented as member function. As far as I know there is no conceptual difference between std::complex and Vector2 regarding addition.

Is there any reason to not use the standard library approach when implementing Vector2 class? Is some real advantage to use one approach or the other or is just a matter of personal preference?

Note: x and y members from Vector2 are public

There is a very strong reason for it to be a non-member function: symmetry between LHS and RHS of an + expression. In the case of std::complex , it is implicitly convertible from a scalar type ( int , double etc), so the following would not work if the operator were a member:

std::complex<double> c1;
std::complex c2<double> = 5.0 + c1; 

whereas the following would:

std::complex c2<double> = c1 + 5.0;

That inconsistency wouldn't make much sense. A non-member binary operator allows the implicit conversions to take place.

Note : In my experience with mathematical vector types, it is often desirable to provide arithmetic operators involving other vector types:

template <typename V>
Vector2 operator+(const Vector2& lhs, const V& rhs)
{
  Vector2 ret = lhs;
  ret += rhs;  // uses member function template operator +=(const V&)
  return ret;
}

template <typename V>
Vector2 operator+(const V& lhs, const Vector2& rhs)
{
  return rhs + lhs;
}

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