1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

overloading operator *

Discussion in 'C++' started by aortizb, Sep 1, 2009.

  1. aortizb

    aortizb New Member

    Joined:
    Sep 12, 2008
    Messages:
    32
    Likes Received:
    0
    Trophy Points:
    0
    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;
    }
    
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    What error do you get?
     
  3. aortizb

    aortizb New Member

    Joined:
    Sep 12, 2008
    Messages:
    32
    Likes Received:
    0
    Trophy Points:
    0
    GNU compiler will produce an error because there is no *= that matches the overloaded operators in std::vector class.
     
  4. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    OK, so instead of A*=B, use A=A*B
     

Share This Page