STHB
STHB

Reputation: 27

Overloading a multiplication operator in a template class array

I'm trying to code a template class for making arrays that has an overloaded multiplication operator. The actual insides of the template class appear fine, however I am having trouble with the overloading of the * operator. I originally had an overloaded operator for multiplying arrays in a regular class, here I am using that first overloaded operator as a base for the template.

This is whats in my header file :

operator * (const Array<T>& a) const;  //*  operator

And this is whats in my main file :

template <class T>
Array<T>::operator * (const Array<T>& a) const
{
   if (num != a.num)
   {
       cout << "Error, arrays not equal!" << endl;
   }

   Array<int> tmp;
   delete[] tmp.data;

   tmp.data = new int[cap];
   tmp.num = a.num;
   tmp.cap = a.cap;

   memcpy(tmp.data, a.data, sizeof(int)*num);


   for(int i = 0 ; i < num ; i++)
   {
       tmp.data[i] = tmp.data[i] * a.data[i];
   }  

   return tmp;
}

The error I am receiving is telling me that something is wrong with tmp. It states "error: cannot convert 'Array' to 'int' in return" in reference to "return tmp" at the end of the function.

I am trying to multiply two arrays (a and c) created in main()

Array <int> d = a * c;

There are error messages relating to Array d, but those also appear to be rooted in the error inside the overloaded operator function. How is tmp being turned into 'int' ?

Upvotes: 0

Views: 1276

Answers (2)

Semyon Burov
Semyon Burov

Reputation: 1172

You need to template Array<int> tmp; as Array<T> tmp;, so that then you memcpy(tmp.data, a.data, sizeof(int)*num); the size of memory area would realy be same. Also, as @Thecocatrice mentioned, add retutn type to you overloaded operator. This will look like

template<typename T>
Array<T> Array<T>::operator *(const Array<T> &a) { ... };

And last. You dont actually need that memcpy. It doesnt make any sence, since you still have loop. Just write:

for(int i = 0 ; i < num ; i++)
{
    tmp.data[i] = data[i] * a.data[i];
} 

Upvotes: 0

The cocatrice
The cocatrice

Reputation: 26

Your function does not have a return type. C++ will therefore default to int. to solve this, make sure the function returns an Array<int> (the type of tmp).

Upvotes: 0

Related Questions