Overloading operators in C++

TVector.h

 

friend TVector operator/(const TVector&, double);//   TVector/double

friend TVector operator*(const TVector&, double);//   TVector*double
friend TVector operator*(double, const TVector&);//   double*TVector
TVector& operator*=(double); // TVector *= double

TVector operator+(const TVector&);//add two vectors
TVector operator-(const TVector&);//subtract two vectors

TVector.cpp

 

//operators
TVector operator/(const TVector &v, double value){

  TVector result;

  result.x = v.x / value;
  result.y = v.y / value;
  result.z = v.z / value;

  return result;
}

TVector operator*(const TVector &v, double value){

  TVector result;

  result.x = v.x * value;
  result.y = v.y * value;
  result.z = v.z * value;

  return result;
}

TVector operator*(double value, const TVector &v){

  return v * value;
}

TVector& TVector::operator*=(double value){

  *this = *this * value;

  return *this;
}

TVector TVector::operator+(const TVector &v){

  TVector result;

  result.x = x + v.x;
  result.y = y + v.y;
  result.z = z + v.z;

  return result;
}

TVector TVector::operator-(const TVector &v){

  TVector result;

  result.x = x - v.x;
  result.y = y - v.y;
  result.z = z - v.z;

  return result;
}

Tagged with:

Leave a Reply

Your email address will not be published. Required fields are marked *

*