Monday, 20 February 2012

Operator Overloading in C++ Part 4

previously we have discussed the different types of operator overloading and the differences between the Member operators and Free operators. In this part we are going to implement a basic * Scalar operator which will multiply each of the Vec3 components by a floating point scalar value. In the .h file we can implement the following definition for the operator
/// @brief * float operator
Vec3  operator*(float _rhs) const;
and for the .cpp file the following
/// @brief * float operator
Vec3 Vec3::operator*(float _rhs) const
{
  return Vec3(m_x*_rhs,m_y*_rhs,m_z*_rhs);
}
Testing this using the following code results in
std::cout<<"b*2== "<<b*2<<"\n";
b*2== [4,6,8] 
However if we try to write the following
std::cout<<"2*a ="<<2*a<<" b*2== "<<b*2<<"\n";
We get the following compiler error error: no match for 'operator*' in '2 * a' This is due to the fact that we have no operator for scalar * Vec3. To solve this problem we can generate a Free function version of the operator and a scale method to scale the vector by a scalar value.
/// @param[in} _s the value to scale components by
Vec3 scale(float _s) const;

Vec3 operator *(float _lhs, const Vec3 &_rhs);

/// in the .cpp file
Vec3 operator *(float _lhs, const Vec3 &_rhs)
{
  return _rhs.scale(_lhs);
}
In most cases it will be best to implement both operators as free functions so we would have the following extra methods
Vec3 operator *(float _lhs, const Vec3 &_rhs)
{
  return _rhs.scale(_lhs);
}

Vec3 operator *(const Vec3 &_lhs,float _rhs)
{
  return _lhs.scale(_rhs);
}
As you can see both methods require the extra scale method, however if we use the free function version we can remove the member operator. In some cases this will not be required (for example if the operands are of the same type)

No comments:

Post a Comment