Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   overloading operator * (http://www.go4expert.com/forums/overloading-operator-t19252/)

aortizb 1Sep2009 09:36

overloading operator *
 
Hello all,

can anyone tell me how can i make the following code to work fine in MVS and GNU compiler? This code will work only for MVS. GNU compiler will generate a building error.

Code:

#include <iostream>
#include <vector>
using namespace std;

template<class T>
const vector<T>&
operator*=(vector<T>& obj1, const T typeVal)
{                             
  for (unsigned i = 0; i < obj1.size(); i++)
    obj1[i] *= typeVal;

  return obj1;
}

template<class T>
const vector<T>
operator*(const vector<T>& obj1, const T typeVal)
{
  return (vector<T>(obj1) *= typeVal);
}

template<class T>
const vector<T>
operator*(const T typeVal, const vector<T>& obj1)
{
  return (obj1*typeVal);
}

int main()
{
  vector<double> x(3,4);
  vector<double> d = x*2.0;
  cout << d[0] << " " << d[1] << " " << d[2] << endl;
  return 0;
}


xpi0t0s 1Sep2009 13:40

Re: overloading operator *
 
What error do you get?

aortizb 1Sep2009 13:43

Re: overloading operator *
 
GNU compiler will produce an error because there is no *= that matches the overloaded operators in std::vector class.

xpi0t0s 1Sep2009 13:51

Re: overloading operator *
 
OK, so instead of A*=B, use A=A*B


All times are GMT +5.5. The time now is 06:26.